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:

 // If x is even 
if (x % 2 == 0) 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).

See also this excellent document on Scribd, and of the course the Wikipedia entry for a more technical description of what can be achieved with boolean operators.

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.

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.