Java: Beware of accidental semicolons in while and for loops!

The following code…

while(cond); {
    // ...
}

…is actually interpreted as

while(cond)
    ; // <-- loop body!

{
    // Separate block statement, not part of the loop!
}

This is because ; is treated as a no-op statement, and braces are optional if the loop body consists of a single statement.

This can have catastrophic consequences, since the block statement is only executed once.

Example: Program enters an infinite loop since i++ is never executed

int i = 0;
while (i < 10); {
    i++;
}

Same issue applies for for loops.

Example: "Hello" printed once since the print statement is not part of the loop body

for (int i = 0; i < 10; i++); {
    System.out.println("Hello");
}

Comments

Be the first to comment!