C Foundations: Control Flow
Decisions and loops in Objective-C are plain C. This lesson covers if, switch, the ternary operator and the three kinds of loops, plus break and continue.
if / else if / else
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
int scores[] = {95, 78, 64, 40};
for (int i = 0; i < 4; i++) {
int score = scores[i];
NSString *grade;
if (score >= 90) {
grade = @"A";
} else if (score >= 75) {
grade = @"B";
} else if (score >= 60) {
grade = @"C";
} else {
grade = @"F";
}
NSLog(@"%d -> %@", score, grade);
}
}
return 0;
}95 -> A
78 -> B
64 -> C
40 -> F
Any non-zero value counts as true, and nil (no object) counts as false. That is why Objective-C code often writes if (name) { … } to mean "if name is not nil".
Tip: Always use braces, even for one-line bodies. A famous 2014 security bug in Apple's TLS code ("goto fail") was caused by a duplicated line under an
ifwithout braces.
The ternary operator
condition ? valueIfTrue : valueIfFalse picks one of two values. It is handy inside NSLog:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
int items = 1;
NSLog(@"You have %d item%@", items, items == 1 ? @"" : @"s");
items = 3;
NSLog(@"You have %d item%@", items, items == 1 ? @"" : @"s");
NSString *nickname = nil;
NSString *shown = nickname ?: @"Guest"; // the ?: shortcut: use left side if non-nil
NSLog(@"Hello, %@", shown);
}
return 0;
}You have 1 item
You have 3 items
Hello, Guest
a ?: b (a GNU/clang extension that Apple code uses a lot) means "a if it is non-zero/non-nil, otherwise b".
switch
switch compares an integer value (including char and enums) against constant cases. Each case needs a break, otherwise execution "falls through" into the next case. Note that you cannot switch on an NSString.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
for (int day = 1; day <= 7; day += 2) {
switch (day) {
case 1:
NSLog(@"%d: Monday, back to work", day);
break;
case 6:
case 7:
NSLog(@"%d: weekend", day);
break;
default:
NSLog(@"%d: a weekday", day);
break;
}
}
}
return 0;
}1: Monday, back to work
3: a weekday
5: a weekday
7: weekend
Cases 6 and 7 share one body by deliberately falling through.
Loops
| Loop | Use it when |
|---|---|
for (init; condition; step) |
you count from one number to another |
while (condition) |
you repeat until something changes, checking first |
do { … } while (condition); |
the body must run at least once |
for (id x in collection) |
you visit the items of a collection (fast enumeration, covered later) |
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
// for: a countdown
for (int i = 3; i > 0; i--) {
NSLog(@"T-minus %d", i);
}
// while: double until we pass 100
int value = 1;
int steps = 0;
while (value <= 100) {
value *= 2;
steps++;
}
NSLog(@"reached %d after %d doublings", value, steps);
// do-while: runs once even though the condition is false
int tries = 10;
do {
NSLog(@"attempt %d", tries);
tries++;
} while (tries < 5);
}
return 0;
}T-minus 3
T-minus 2
T-minus 1
reached 128 after 7 doublings
attempt 10
break and continue
break leaves the loop immediately; continue skips to the next iteration.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
int readings[] = {12, -1, 15, 0, 99, 18};
int count = sizeof(readings) / sizeof(readings[0]);
int sum = 0;
for (int i = 0; i < count; i++) {
if (readings[i] < 0) {
continue; // skip invalid readings
}
if (readings[i] == 99) {
NSLog(@"end marker at index %d", i);
break; // stop at the marker
}
sum += readings[i];
}
NSLog(@"sum of valid readings: %d", sum);
}
return 0;
}end marker at index 4
sum of valid readings: 27
sizeof(readings) / sizeof(readings[0]) is the C idiom for "number of elements in a fixed array".
Test yourself
What happens if a case in a switch has no break?
- A compile error
- Execution falls through into the next case
- The switch restarts
- The program crashes
What does name ?: @"Guest" evaluate to when name is nil?
- nil
- @"Guest"
- an empty string
- a crash
Which loop always runs its body at least once?
- for
- while
- do-while
- for-in