As with most programming constructs, loops have their own set of potential pitfalls. In this section we will address areas that can present problems to the unwary developer.
One common problem occurs when programmers use a semicolon after every statement. For example, the following statement results in an infinite loop because of the extra semicolon:
int i = 1; while(i < 10) ; i++;
The semicolon on a line by itself is the empty statement. This statement does nothing. However, in this example it constitutes the body of the while loop. The increment statement is not part of the while loop. It is the first statement that follows the while loop. Indention, while desirable, does not make the statement a part of the loop. Thus, i
is never incremented and the logical control expression will always return true.
Failure to use a block statement for the body of a loop can be a problem. In the following example we attempt to calculate the sum of the product of the numbers from 1 to 5. However...