The C Programming Language: Chapter 3
Chapter three of The C Programming Language focuses on control flow. If you're already familiar with another programming language, most of this chapter should seem pretty familiar to you. This post is quickly going to go over some of the more unusual control flow statements which might be new to you.
Switch statement
Switch statements are fairly common, however there are some languages, notably Python, which don't include a switch statement. In C switch statements take a single expression, and then compare the result against multiple cases. If a case matches the statements following the matching case are executed. For example:
switch (next_char) {
case 'a':
t[j++] = '\a';
break;
case 'b':
t[j++] = '\b';
break;
case 'f':
t[j++] = '\f';
break;
case 'n':
t[j++] = '\n';
break;
case 'r':
t[j++] = '\r';
break;
case 't':
t[j++] = '\t';
break;
case 'v':
t[j++] = '\v';
break;
}
Note: in the example above break;
is used to exit the switch statement to
avoid checking subsequent cases.
Infinite for loops
It's actually possible to omit every expression in a for loop. For example:
#include <stdio.h>
int main()
{
int seconds;
for (;;) {
seconds = time('\0') % 60;
if (seconds % 10 == 0)
break;
else
sleep(1);
}
printf("seconds: %d\n", seconds);
return 0;
}
The code above will loop until seconds
is divisible by 10, at which point
break;
is used to exit the for loop. While the code above is valid, the for
loop could easily be re-written as follows:
for (seconds = time('\0') % 60; seconds % 10 != 0; seconds = time('\0') % 60)
sleep(1);
do-while loops
Another slightly unusual control flow statement is the do-while
loop. This
behaves in a similar way to a normal while loop, except the expression comes
after the statements. For example:
do {
seconds = time('\0') % 60;
sleep(1);
} while (seconds % 10 != 0);
Note: because the condition is evaluated at the end, the statements preceding it will always be run at least once.
goto and labels
C also supports goto
statements. These can be used to jump to a corresponding
label. For example
if (error)
goto handle_error;
handle_error:
fprintf(stderr, "Something bad happended...\n");
Generally goto
statements are rarely used, however it's worth knowing how
they work in case you do run into one.