Learn Objective-C: What Goes Inside the if() Statement
The if() statement tests for a boolean (true or false) condition, and executes the following code accordingly. The condition that falls within the parentheses is the boolean condition that determines which code path your program will take. But what exactly can go inside the inside the parentheses? As it turns out, any operator-based expression can be used:
- The double-equals (==): The double-equals is used for comparison (x==5 is logically the same as “x is equal in value to 5″, while the single equals, x=5, assigns the value of 5 to the variable x). This can be used to test for the result of an expression:
if(x % 2 == 0) // If x is even NSLog(@”x is even.”); else NSLog(@”x is odd.”);
Make sure that you use the double equals for a comparison; a single equals is only used for assignment, and unless you are assigning zero to a variable, the expression will always be true (because any non-zero expression is considered true).
- The not equal to (!=): The not equal to operator is the exact opposite of the double-equals; if the left part is not equal to the right, then execute the following code.
if (x != 5) NSLog(@”x does not equal 5.”);
- The Greater-than, Less-than (<, >, <=, >=): These operators work just like they do in real life. They are the less than, greater than, less than or equal to, and greater than or equal to operators, which have not changed since high-school algebra.
if (x > 5) NSLog(@”x is greater than 5.”); else if (x < 5) NSLog(@”x is less than 5.”); else NSLog(@”x is equal to 5.”);
- Boolean Operators (&&, ||, !): Three symbols (or pairs of symbols) can also be used to express a boolean condition. These are the and (&&), the or (||), and the not (!). These are just as logical as the if() statement itself:
if ((x >= 5) && (y < 10)) NSLog(@”x is greater than or equal to 5, AND y is less than 10.”); if (x == 3 || y == 6) NSLog(@”x is equal to 3 OR y is equal to 6″); if (!(x > 2 && y < 5)) NSLog(@”x is NOT greater than 2 AND y is NOT less than 5″);
When using these expressions in conjunction, don’t hesitate to use parentheses or spaces to make your purpose clear. Although the operator precedence table tells us that the internal parentheses were not needed in the last example, their presence helps clarify the logical intent.
By the way, the Conditional Operator is an oddity (among operators) that could save you a bit of typing.
This post is part of the Learn Objective-C in 24 Days course.
Author: Feifan Zhou