Coding Conventions - Examples - Looping and Control Structures

Looping and Control Structures

The use of logical control structures for looping adds to good programming style as well. It helps someone reading code to better understand the program's sequence of execution (in imperative programming languages). For example, in pseudocode:

i = 0 while i < 5 print i * 2 i = i + 1 end while print "Ended loop"

The above snippet obeys the naming and indentation style guidelines, but the following use of the "for" construct may be considered easier to read:

for i = 0, i < 5, i=i+1 print i * 2 print "Ended loop"

In many languages, the often used "for each element in a range" pattern can be shortened to:

for i = 0 to 5 print i * 2 print "Ended loop"

In programming languages that allow curly brackets, it has become common for style documents to require that even where optional, curly brackets be used with all control flow constructs.

for (i = 0 to 5) { print i * 2; } print "Ended loop";

This prevents program-flow bugs which can be time-consuming to track down, such as where a terminating semicolon is introduced at the end of the construct (a common typo):

for (i = 0; i < 5; ++i); printf("%dn", i*2); /* The incorrect indentation hides the fact that this line is not part of the loop body. */ printf("Ended loop");

...or where another line is added before the first:

for (i = 0; i < 5; ++i) fprintf(logfile, "loop reached %dn", i); printf("%dn", i*2); /* The incorrect indentation hides the fact that this line is not part of the loop body. */ printf("Ended loop");

Read more about this topic:  Coding Conventions, Examples

Famous quotes containing the words structures, looping and/or control:

    If there are people who feel that God wants them to change the structures of society, that is something between them and their God. We must serve him in whatever way we are called. I am called to help the individual; to love each poor person. Not to deal with institutions. I am in no position to judge.
    Mother Teresa (b. 1910)

    A book is like a man—clever and dull, brave and cowardly, beautiful and ugly. For every flowering thought there will be a page like a wet and mangy mongrel, and for every looping flight a tap on the wing and a reminder that wax cannot hold the feathers firm too near the sun.
    John Steinbeck (1902–1968)

    Being a parent is such serious business that we dare not take it too seriously. Children are inherently funny. So are parents. We all are at our funniest when we are desperately struggling to appear to be in control of a new situation.
    Lawrence Kutner (20th century)