Title here
Summary here
Branching with if
and else
in Objective-C is straightforward.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Here's a basic example.
if (7 % 2 == 0) {
NSLog(@"7 is even");
} else {
NSLog(@"7 is odd");
}
// You can have an `if` statement without an else.
if (8 % 4 == 0) {
NSLog(@"8 is divisible by 4");
}
// Logical operators like `&&` and `||` are often useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0) {
NSLog(@"either 8 or 7 are even");
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
int num = 9;
if (num < 0) {
NSLog(@"%d is negative", num);
} else if (num < 10) {
NSLog(@"%d has 1 digit", num);
} else {
NSLog(@"%d has multiple digits", num);
}
}
return 0;
}
To run the program, compile and execute it:
$ clang -framework Foundation if-else.m -o if-else
$ ./if-else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that in Objective-C, you need parentheses around conditions, and braces are required for multi-line blocks. Single-line blocks can omit braces, but it’s generally recommended to always use them for clarity and to prevent errors.
Objective-C does have a ternary operator (?:
), which can be used for simple conditional expressions. However, for more complex conditions, a full if
statement is often clearer and more maintainable.