#include <stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d\n",i);
return 0;
}
Why is the increment of i
done after the comparison in each test case?
#include <stdio.h>
int main()
{
int i=0;
while(i++,i<=8);
printf("%d\n",i);
return 0;
}
Why is the increment of i
done after the comparison in each test case?
i <= 8
succeeds for the last time when i = 8
.
In the last iteration, i++
is executed, then i <= 8
fails because i = 9
.
Note that the ,
is a sequence point, so i++
is absolutely guaranteed to be executed before i <= 8
. Not so for similar constructs.
It's not. Your loop condition is i <= 8
, it is first non-true when i
reaches 9 (you're incrementing i
by 1 each time, so it will be exactly 9). That is why it prints 9.
To reach to the print()
statement, while
loop must end. The terminating condition, controlling expression should evaluate to false (or, in other words, until the controlling expression compares equal to 0), i.e., it will be false only when i <= 8
; evaluates to false. For a value of i
as 9
, that happens.
Next line, the value of i
, gets printed. So, you see 9
.
Increment of i
is not done after the comparison in each test case. i++
is executed first and after that the comparison is done.
This is because when expressions are separated using commas in C, the expressions are evaluated from left to right and the value of the last expression becomes the value of the total comma separated expression.
So the value of
i++,i<=8
is actually the value of i<=8
and that comparison is done only after i++
is executed.
So the while
loop here
int i=0;
while(i++,i<=8);
is equivalent to
for(i=1; i<=8; i++);
Hence the control exits the loop only when i
is greater than 8
. Since i
is incremented by 1
on each iteration, this means that the loop is over when i
becomes 9
.
You started i = 0
and using while ( i++, i<=8 )
loop you incremented it's value until 8
and when it's increased one more time i = 9
, then loop condition became false
and breaks the loop with i = 9
. And that's why now, when you print i
's value, it gave you 9.