Java Reference
In-Depth Information
Why 11? Have another look. Did you spot the semicolon at the end of the for
loop header? This loop is actually a loop with an empty body.
for (i = 1; i <= 10; i++)
;
The loop does nothing 10 times, and when it is finished, sum is still 0 and i is 11.
Then the statement
sum = sum + i;
is executed, and sum is 11. The statement was indented, which fools the human
reader. But the compiler pays no attention to indentation.
Of course, the semicolon at the end of the statement was a typing error. Someone's
fingers were so used to typing a semicolon at the end of every line that a semicolon
was added to the for loop by accident. The result was a loop with an empty body.
242
243
Q UALITY T IP 6.2: Don't Use != to Test the End of a
Range
Here is a loop with a hidden danger:
for (i = 1; i != n; i++)
The test i != n is a poor idea. How does the loop behave if n happens to be zero
or negative?
The test i != n is never false, because i starts at 1 and increases with every step.
The remedy is simple. Use <= rather than != in the condition:
for (i = 1; i <= n; i++)
A DVANCED T OPIC 6.2: Variables Defined in a for Loop
Header
As mentioned, it is legal in Java to declare a variable in the header of a for loop.
Here is the most common form of this syntax:
Search WWH ::




Custom Search