Many novice C programmers seem to have trouble understanding the side effects originating from a basic flow control mechanism such as the 'for' cycle. This article is an attempt at clarifying these concepts once and for all.
For Loop Syntax in C-Like Programming Languages
In all C-like programming languages, the for construct is composed of three parts, each divided by a semicolon:
- In the first section, the initialization, we initialize an index variable (which is usually being named i, j or k) to its initial value;
- In the second part, we test whether a variable (usually the same we have just initialized in the first part) satisfies a certain condition: if it does, we enter the loop one more time, otherwise we exit from it;
- In the third and last part, we update the variable — usually by incrementing or decrementing it by 1.
How the For Loop Works
Knowing the syntax of the for loop is not enough: in fact, what is usually the major source of confusion among novice programmers is not the syntax itself, but rather the runtime behavior of the construct.
for(i = 0; i < 10; i++) { printf("%d ", i); }
The snippet above is a very basic example of such a loop. Let's see what happens when we run this code, assuming that the block enclosed within curly brackets doesn't otherwise modify the value of the index i:
- The variable i is initialized to 0;
- The test "i < 10" is performed, and the code enclosed in curly brackets is executed if the test is successful, exiting the loop otherwise;
- The index i is incremented (i++);
- The points 2-3 are repeated until the test "i < 10" fails and we exit the loop.
As a result, as it can be easily verified, the output would be:
Notice that the number 10 is not being printed, because i is first incremented from 9 to 10, and then tested. When we exit the loop, we do so because the condition i < 10 is no more true, since i is now equal to 10.
Special For Loops: While Loops and Infinite Loops
The peculiar syntax of the for loop can be adapted to a wide variety of situations, and can even used to behave in the exact same fashion as a while() loop. For instance, consider what happens when we write:
This somewhat cryptic code is equivalent to while(i < 10) { ... } in that, since the first and last part are absent, we simply test for i < 10 without initializing nor updating the variable. For this reason, we say that the while() loop is nothing but a special case of the for loop.
When using the for construct, novice programmers must always be careful to choose a condition that is guaranteed to terminate the loop at some point in time: the risk is of incurring in a so-called infinite loop. Consider for instance this piece of code:
which is a clear programming error that will loop indefinitely and consume all the available processor time until it will be manually terminated by the user.
Join the Conversation