Reputation: 71
for(;;)
statement is an empty statement. Though being an empty condition, compiler should treat it as null
statement which is equivalent to 0
, i.e FALSE. Therefore, according to me, it should not get evaluated.
But to my surprise, compiler sends the true signal.
Kindly explain.
Upvotes: 1
Views: 165
Reputation: 148
The Infinite Loop:
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop. Happy Coding :-)
Upvotes: 4
Reputation: 121407
C standard states that if the condition is present, then it should treated as if it had a non-zero value.
6.8.5.3, p2 The for statement for ( clause-1 ; expression-2 ; expression-3 )
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
(emphasis mine)
This is inconsistent with while
loop though as the conditional expression can't be left empty in a while loop. But that's how C is on many aspects :)
Upvotes: 9
Reputation: 106092
A null statement is not equivalent to 0
or false
. Omitting all expressions from for
loop make it an equivalent to while(1)
.
When the conditional statement in for
loop is empty, then you need to specify that in loop body.
Upvotes: 2