Loops - a comparison of goto, while and for
Archive - Originally posted on "The Horse's Mouth" - 2011-08-10 06:54:57 - Graham EllisAlmost every program you write, in any language, will have repeating code in it in the form of a loop. Programs without loops are limited to really simple "read a piece of data, calculate on it and print a result" tasks, and ever with them there will be loops within the function calls that you make if not within your own code.
In my early days of programming, I maintained a number of programs that made heavy use of the goto loop, where an instruction to jump backwards in the program to a labelled (named) line caused the piece of code between the label and the goto statement to be repeated multiple times; the goto was accompanied by a conditional which (once it became false) allowed the code to carry on beyond the loop.
goto has gone out of fashion / been replaced by other mechanisms which are less error prone and easier to follow. During yesterday's C course, we ended up talking about gotos, and I wrote an example in class to illustrate the structure. [full source].
Here are the key elements of the goto loop:
int siblings = 17;
[more code]
looper:
[code to be repeated]
if (siblings > 1) {
siblings = siblings - 1;
goto looper;
}
The while loop is a massive improvement on goto. There's no danger of badly nested loops, and no need for the maintainance programmer to be desparately seaching up and down the source for a label. I wrote a comparatibe example - [full source]; the key elements are:
int siblings = 17;
[more code]
while (siblings > 0) {
[code to be repeated]
siblings = siblings - 1;
}
That's "better" but not "best". There are still three distinct places you need to look in the code to find out the start point, step and end point of the loop and they can be well separated from each other by intermediate code. But at least you know it's a loop, which you don't initially with the goto.
So what's best? A for loop, where the initial value, end point and step are all a single statement. It turns out to be very easy to conver a while into a for - simply change the word while to for and move the initial setting and increment into the statement, like this:
int siblings;
[more code]
for (siblings = 17; siblings > 0; siblings = siblings - 1) {
[code to be repeated]
}
You can see the full final code (and I show some shortenings such as the use of ++ and -- too) [here].