Reputation: 341
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?
int main(void) {
int a = 0;
while(a++ < 10){
printf("%d ", a);
}
printf("\n%d ", a);
return 0;
}
1 2 3 4 5 6 7 8 9 10
11
Upvotes: 2
Views: 1056
Reputation: 7006
The post increment operator increments the value of the variable before it after the execution of the statement.
Let's take an example,
int k = 5 ;
printf("%d\n", k++ );
printf("%d", k );
will output
5
6
because in the first printf()
, the output is shown and only after that, the value is incremented.
So, lets look at your code
while(a++ < 10)
it checks a < 10
and then after that, it increments a
.
Lets move to a few iterations in your loop.
When a
is 9
, the while loop checks 9 < 10
and then increments a
to 10, so you will get output for that iteration as 10, and similarly, for the next iteration, it will check 10 < 10
but the while loop does not execute, but the value of a
is incremented to 11
and thus, in your next printf()
, you get output as 11
.
Upvotes: 3
Reputation: 81976
Let's look at a simpler piece of code to show what a++
does.
int a = 0;
int b = a++;
printf("%d %d\n", a, b);
I think that you'd expect this to output 1 1
. In reality, it will output 1 0
!
This is because of what a++
does. It increments the value of a
, but the value of the expression a++
is the initial pre-incremented value of a
.
If we wanted to write that initial code at the top of my answer as multiple statements, it would actually be translated to:
int a = 0;
int b = a;
a = a + 1;
printf("%d %d\n", a, b);
The other increment that we have access to is pre-increment. The difference there is that the value of the expression ++a
is the value of a
after it was incremented.
Upvotes: 2
Reputation: 3419
Because it's post-increment. The compiler will first evaluate a<10
and THEN increment a
by 1
.
Upvotes: 1
Reputation: 62062
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.
Upvotes: 4