Reputation: 1904
I have the following code:
int main()
{
char i = 0;
for (; i++; printf("%d", i));
printf("%d", i);
return 0;
}
It successfully compiles and prints 1
. I am new to C and I don't understand this. I thought i++ will always be true and so it will be an infinite loop.
Can someone please explain this to me?
Upvotes: 1
Views: 185
Reputation: 1
for (; i++; printf("%d", i));
is legal C code, but is not idiomatic C code. Real C programmers never code like this (but can understand what happens). Read n1570 (it practically is the C standard) §6.8.5.3 for the meaning of for
:
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 identifiers 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.158)
2 Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Footnotes
158) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration, such that execution of the loop continues until the expression compares equal to 0; and expression-3 specifies an operation (such as incrementing) that is performed after each iteration.
So, in your case, the controlling expression (the "expression-2
" in the C standard) is (wrongly) i++
. It happens to be false on the first time the loop is taken.
If you replace i++
by ++i
the condition stays true for 255 times on my Linux computer (since I have unsigned chars on 8 bits).
If your computer has signed chars, you technically have some undefined behavior, because you have a signed overflow. So be very scared and read Lattner's blog on UB!
I am new to C and I don't understand this.
Then you should read some C reference site, sometimes refer to the C11 standard n1570, read good books on C programming (perhaps even read good introduction to programming, such as SICP - which does not use C), and learn how to debug small programs. If you use some GCC compiler, be sure to enable all warnings and debug info, so compile with gcc -Wall -Wextra -g
.
Upvotes: 2
Reputation: 9619
i++
is post-increment. So at the time of checking the statement, the value of i
is 0
, which is false
. Hence, the loop breaks.
Upvotes: 3