Node:The flexibility of for, Next:Terminating and speeding loops, Previous:for, Up:Loops
The flexibility of for
As mentioned above, C's for
construct is quite versatile. You can
use almost any statement you like for its initialization,
condition, and increment parts, including an empty
statement. For example, omitting the initialization and
increment parts creates what is essentially a while
loop:
int my_int = 1; for ( ; my_int <= 20; ) { printf ("%d ", my_int); my_int++; }
Omitting the condition part as well produces an infinite
loop, or loop that never ends:
for ( ; ; ) { printf("Aleph Null bottles of beer on the wall...\n"); }
You can break out of an "infinite loop" with the break
or
return
commands. (See Terminating and speeding loops.)
Consider the following loop:
for (my_int = 2; my_int <= 1000; my_int = my_int * my_int) { printf ("%d ", my_int); }
This loop begins with 2, and each time through the loop, my_int
is squared.
Here's another odd for
loop:
char ch; for (ch = '*'; ch != '\n'; ch = getchar()) { /* do something */ }
This loop starts off by initializing ch
with an asterisk. It
checks that ch
is not a linefeed character (which it isn't, the
first time through), then reads a new value of ch
with the
library function getchar
and executes the code inside the curly
brackets. When it detects a line feed, the loop ends.
It is also possible to combine several increment parts in a
for
loop using the comma operator ,
. (See The comma operator, for more information.)
#include <stdio.h> int main() { int up, down; for (up = 0, down=10; up < down; up++, down--) { printf("up = %d, down= %d\n",up,down); } return 0; }
The example above will produce the following output:
up = 0, down= 10 up = 1, down= 9 up = 2, down= 8 up = 3, down= 7 up = 4, down= 6
One feature of the for
loop that unnerves some programmers is
that even the value of the loop's conditional expression can be altered
from within the loop itself:
int index, number = 20; for (index = 0; index <= number; index++) { if (index == 9) { number = 30; } }
In many languages, this technique is syntactically forbidden. Not so in the flexible language C. It is rarely a good idea, however, because it can make your code confusing and hard to maintain.