简体   繁体   中英

Value after the while loop with post-increment

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.

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 .

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.

Because it's post-increment. The compiler will first evaluate a<10 and THEN increment a by 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM