| Each function definition can only have one loop, with a single exception. You may use two nested for-loops to loop over a two-dimensional array. |
| A function that contains a loop must not also use recursion. |
If code is only performed at the end of the last iteration of a loop, then it should be written after the loop [LOOP-END]
Look at the following example.
int loopdemo(int n)
{
for(int i = 0; i < n; i++)
{
doSomething(i);
if(i == n-1)
{
finish(i+1);
}
}
}
Notice that statement finish(i+1) is only done at the end of the
last iteration of the loop. This function should be written
as follows.
int loopdemo(int n)
{
for(int i = 0; i < n; i++)
{
doSomething(i);
}
finish(n);
}
|
Do not change the value of a for-loop control variable in the loop body [FOR-BODY-1]
A for-loop
control variable (any variable that is modified in the third
part of a for-loop heading) should only be modified in the for-loop heading,
not in the body of the loop. For example, do not write
for(i = 1; i < n; i++)
{
...
i = n;
...
}
If you want to break out of a loop, use break or return.
|
Do not change a for-loop end value in the loop without justification [FOR-BODY-2]
Do not change the end-value of a for-loop just as a way to get
out of the loop. For example,
for(i = 1; i < n; i++)
{
...
if(condition)
{
n = 0;
}
...
}
is not a good way to cause the loop to end. If you want to
exit a for-loop, use break or return.
|