1

C++17

Could someone explain how

int number{5};
number = (number++) + 10;

Gives an output of 15 while

int number {5};
number = (++number) + 10;

Gives an output of 16?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Andrew Mbugua
  • 437
  • 1
  • 6
  • 16

3 Answers3

9

Before P0145 was adopted (in C++17), the first example had undefined behaviour. Anything could happen.

Before C++11, both had undefined behaviour.

In C++17, neither has undefined behaviour. That doesn't mean it's code you want to be writing.

The explanation of your output is simple, if we understand the difference between postfix and prefix increment:

Case 1

  • number++: number becomes 6 but the expression evaluates to 5
  • ten is added to the expression
  • the result (15) is stored in number

Case 2

  • ++number: number becomes 6 and the expression evaluates to 6
  • ten is added to the expression
  • the result (16) is stored in number
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    The pre-increment version has been well-defined since C++11, since the side-effect of the increment is sequenced-before its value computation which is sequenced-before the assignment's side-effect. – walnut Jan 07 '20 at 18:22
  • @walnut Fair, I was considering the whole question as one program – Lightness Races in Orbit Jan 07 '20 at 18:32
0

Pre increment increments the value and returns the incremented result. Post increment returns the value before the increment, then increments the variable.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
0

Unary post-increment is executed after the statement executed. so, the number is added first and then number is 15. But in pre-increment case the unary operator excited first then the current statement is resolved and result is calculated to 16.

More information: https://en.cppreference.com/w/cpp/language/operator_incdec

int number{ 5 }; 
01013C88 mov dword ptr [number],5 
number = (number++) + 10; 
01013C8F mov eax,dword ptr [number] 
01013C92 add eax,0Ah 
01013C95 mov dword ptr [number],eax 
01013C98 mov ecx,dword ptr [number] 
01013C9B add ecx,1 
01013C9E mov dword ptr [number],ecx 

Assmebly code show the two time addition

Build Succeeded
  • 1,153
  • 1
  • 10
  • 24
  • this has nothing to do with when "the statement executed". The link you should be giving is https://en.cppreference.com/w/cpp/language/eval_order – Cubbi Jan 07 '20 at 19:55
  • int number{ 5 }; 01013C88 mov dword ptr [number],5 number = (number++) + 10; 01013C8F mov eax,dword ptr [number] 01013C92 add eax,0Ah 01013C95 mov dword ptr [number],eax 01013C98 mov ecx,dword ptr [number] 01013C9B add ecx,1 01013C9E mov dword ptr [number],ecx Assmebly code show the two time addition – Build Succeeded Jan 08 '20 at 05:18