简体   繁体   中英

Confusion about increment operator with postfix

I was practicing increment operator with its two varieties prefix and postfix. For fun, I wrote the following program which has left me puzzled. The main body of the program is as follows:

int a=10;
a=a++; 
cout << a; 

  1. The output I got is 10. First I thought it's true, as the assignment is done first and then the value of a is incremented by 1. So yes output should be 10 as it is shown.

  2. But the seconds later I thought it should be 11. Because when the second statement is completed, even though a was assigned to 10, immediately we also incremented it by 1. So the output should be 11. What's going wrong here? Thanks.

You can think of the code like this:

int a = 10;
int temp = a++;
a = temp;
cout << a;

Both the left and right hand sides of an assignment have to be calculated before the actual assignment, which means the side effect from incrementing it will be calculated before the assignment (see this answer ). So, what's really happening is that a++ returns 10, then increments a to 11, but then a is being set to that old value of 10 , so nothing happens in the end.

In your code:

int a=10;//assign value

a=a++;//assign then increase means a = 10 (intermediatly a=11) but it assign value before that.

cout << a; //print

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