What happens when one places a semi-colon after a while loop's condition?
16,223
Solution 1
while (age == 5);
gets stuck into an infinite loop. In c ;
is a null terminator. The compiler assumes that the above loop has only one statement that is ;
which causes the loop to be iterated over infinitely.
Solution 2
a statement consisting of only
;
is a null statement. It is the same as a block (also called compound statement) with nothing inside
{
}
They both perform no operations.
Comments
-
Dot NET over 1 year
I've come across a situation like this a few times:
while (true) { while (age == 5); //What does this semi-colon indicate? //Code //Code //Code }
The
while(true)
indicates that this is an infinite loop, but I have trouble understanding what the semi-colon after thewhile
condition accomplishes, isn't it equivalent to this?:while (age == 5) { } //Code //Code
In other words, does it mean that the
while
loop is useless as it never enters the block?