+ 1

Doing A=A++ in c++ is useless?

I tried to do a = 0; and then a=a++; cout<<a; and a value is 0 instead of 1

26th Mar 2018, 10:44 PM
Monkeypuros
Monkeypuros - avatar
3 Answers
+ 8
a=a++ is definitely undefined behavior. a might end up with either 0 or 1 depending on the order the compiler decides to assign those values. It could pick a=a first followed by a++ yield 1. But, it could just as easily pick grab the 0, a++, store the 0 in a.
26th Mar 2018, 11:07 PM
John Wells
John Wells - avatar
+ 6
In order to perform math, the values are stored in hardware registers of the processor. The compiler would generate load a into register, load 1 into second register, add first register into second, store second register into a, store first register into a.
27th Mar 2018, 12:05 AM
John Wells
John Wells - avatar
+ 1
Thanks for your answer but I still do not understand it. In the second case that you mention, when a returns 0, I do not understand how can be 0 stored in a. First you said that the compiler does two steps: a=a and a++. If a=a is done first at the end a should be 1 because a++ is done after and if a++ is done before, a should also be 1 at the end because after a++ a should be 1 and a=a should not change a's value. Im missing something. The compiler can save a's value somewhere and after doing a++ store that value on a again?
26th Mar 2018, 11:55 PM
Monkeypuros
Monkeypuros - avatar