Reputation: 781
I came across the following question :
How many times will the following for loop run -
for(;0;)
printf("hello");
I executed and it runs 1 time . I am not able to understand how?
Upvotes: 2
Views: 234
Reputation: 121357
This will not execute even for 1 time. I guess you have a bad compiler?
Ok. I think you are using Turbo C ;-)
EDIT:
From C99 standard:
6.8.5.3 The for statement 1 The statement
for ( clause-1 ; expression-2 ; expression-3 )
statement behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.134)
It clearly states that condition is evaluated first before executing the loop. Any standard conforming compiler should not execute the loop for(;0;) {}
even once.
Upvotes: 5
Reputation: 11889
for loops are defined as:
for(startExpression; testExpression; countExpression)
{
block of code;
}
Decoding:
for(;0;)
Means
Edited to show correct for loop decoding.
Upvotes: 1
Reputation: 77866
Since the expression is 0, it is taken to be false. So, in this case the loop runs 0 times.
Upvotes: 0
Reputation: 2838
The code as written above will never enter the for loop.
Check the code on ideone link.
My be this not what you have in your souce code, you probably typed a ;
after for
without noticing it like this:
for(;0;);
printf("hello");
In that case your program will print "hello".
Upvotes: 0
Reputation: 23550
Either the code you copied here is not really what is in your .c file or you have a buggy compiler.
Maybe you have an additional semicolon?: for(;0;); printf("!");
will print once.
Upvotes: 5