Learn Objective-C: Conditional Operator

The conditional operator is rather strange, but is very useful. (By the way, an operator is something that acts upon two or more values, such as the addition + operator.) In many cases (or at least frequent enough for them to make up a new operator), programmers have had to determine the largest or the smallest of two values, and use the corresponding (largest or smallest) value. Normally, the code would be like this:

if (number1 > number2)
     return number1;
else
     return number2;

This became cumbersome. Introducing, the conditional operator:

return (number1 > number2) ? number1 : number2;

This does the same thing as the code above. The parts in bold are the required syntax; any valid expression, constant, or variable can be placed in between.

There are three parts to the conditional operator: the condition, and the two “paths”.

The condition is a boolean condition, one that would otherwise trigger an if-statement. If that is true, number1 is returned; otherwise number2 is returned.

That’s all there is to it.

This post is part of the Learn Objective-C in 24 Days course.

0 comments


Or enter your name and Email
No comments have been posted yet.