|
|
|
The for loop is, in ANSI C like in other programming languages, a very important flow control mechanism which novice programmers usually have trouble understanding.
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 LanguagesIn all C-like programming languages, the for construct is composed of three parts, each divided by a semicolon: for(initialization; test; update) { ... }
How the For Loop WorksKnowing 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:
As a result, as it can be easily verified, the output would be: 0 1 2 3 4 5 6 7 8 9 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 LoopsThe 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: for(;i < 10;) { ... } 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: for(;;); 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.
The copyright of the article Introduction to 'For' Loops in C in C Programming is owned by Dario Borghino. Permission to republish Introduction to 'For' Loops in C in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|