Please explain me why the last printf gives value 11? I really don't understand why it happened. When a = 10 the condition is not fulfilled so why this value has changed to 11? Incrementation goes as soon as the condition is checked?
Code:
int main(void) {
int a = 0;
while(a++ < 10){
printf("%d ", a);
}
printf("\n%d ", a);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
11
Let's look at a++ < 10
when a
is equal to 10
.
The first thing that will happen is 10 < 10
will be evaluated (to false), and then a
will be incremented to 11
. Then your printf
statement outside the while
loop executes.
When the ++
comes on the right hand side of the variable, it's the last thing evaluated on the line.
Try changing a++ < 10
to ++a < 10
, rerunning your code, and comparing the results.