Only omit parts of the heading with good reason
Consider this loop.
int k = 0; for(; k < n; k++) { ... }A for-loop heading is intended to contain all of the code to control one of the variables. By moving the initialization of k out of the for-loop heading, you make the program a little more difficult to read. Instead, write int k; for(k = 0; k < n; k++) { ... }The standards require you to do that when sensible. |
Control one variable in a for-loop heading.
A for-loop is convenient for computing powers.
Here is a sensible power function.
// power(x,n) returns x to the n-th power. // // Requirement: n > 0. double power(double x, int n) { double p = x; for(int k = 2; k <= n; k++) { p = p * x; } return p; }There are two loop-control variables, k and p. Notice that all of the code to initialize, update and test k is in the for-loop heading, as it should be. That makes the loop easy to understand: it says to do statement p = p*x for each value of k from 2 to n. What about the following version? // power(x,n) returns x to the n-th power. // // Requirement: n > 0. double power(double x, int n) { double p = x; for(int k = 2; k <= n; p = p * x) { k++; } return p; }That works, but it is much more difficult to understand than the previous version. To make your code easier to understand, concentrate on one main control variable in a for-loop heading. The standards require you to do that. |
Do not change the value of a for-loop control variable in the loop body.
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.
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. |
See the standards for loops for more detail.