For Loop Variations
Last week, we
examined the structure of the for
loop. Today we will
look at some for
loop idioms.
Infinite loop
If you omit the initialization, condition and
action expressions, you get an infinite loop:
for (;;) {
NSLog(@":-)");
}
Missing loop expression
Sometimes, there's no need to initialize a variable before looping, so
the initialization expression is omitted:
char *process_line(char *buffer) {
for ( ; *buffer != '\n'; buffer++) {
/* do something with characters */
}
return buffer;
}
Similarly the condition or action expressions are
sometimes omitted.
Nested loops
When building or processing tables of information, put one
for
loop inside another:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
NSLog(@"%d X %d = %d", i, j, i * j);
}
}
Parallel iteration
You can use multiple loop counter variables by using the comma
(,
) operator to squeeze multiple expressions into
initialization and action:
int i, j;
for (i = 0, j = 9; i < 10; i++, j--) {
destination[i] = source[j];
}
There's a gotcha with the initialization expression however:
only one loop counter variable can be declared there. It seems logical
to do this:
for (int i = 0, int j = 9; i < 10; i++, j--) ...
but unfortunately you can only do this:
int j;
for (int i = 0, j = 9; i < 10; i++, j--) ...
Next week, we'll
look at the Objective-C 2.0 for...in
loop.