Reputation: 3
char i;
for (i = 1; i < 10, i++;)
{
cout << (i+1) << endl;
}
return 0;
I understand that for loop has the following syntax:
for(initialization; condition; increment)
{
}
As I run the debug, why it never checks the condition and it eventually stops at i = 0?
(Thank you Damien and Andars, I don't know why the "on purpose" statement was removed, but you interpret my question correctly. Could someone explain why the complier skips the condition before the comma, and why the loop stop at i = 0 instead of looping forever? Thanks!)
Upvotes: 0
Views: 119
Reputation: 5647
I believe he is indicating that he wrote the code that way on purpose.
To answer, i++ will always return true. The last value is the value that matters with comma separated statements, so the loop will not stop.
Edit for elaborations:
It isn't simply using a logical or, it disregards what is before the comma and only takes the last value. The value of anything non-zero is considered true, and since i starts at 1, and goes up, it will always be non-zero (until it overflows and wraps back around, which explains why i ends at 0).
If you say:
x = 4, 5, 6;
x will be equal to 6, the last value.
Upvotes: 2
Reputation: 1404
It seems to me also that the code was written incorrectly on purpose. As others have mentioned, the comma operator will discard the value of the i<10
and only i++
will be evaluated as condition. This will return true until i
overflows (values only from -127 to 127) and ends up at -1
, when i++
will return 0 and the loop exits. Thus the final value for i will be 0.
Upvotes: 1
Reputation: 4738
Change to
for (i = 1; i < 10; i++) //Notice correct placement of ;
Upvotes: 1
Reputation: 50667
Change
for (i = 1; i < 10, i++;)
to
for (i = 1; i < 10; i++)
Upvotes: 1