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?
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?
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:
number++
: number
becomes 6 but the expression evaluates to 5number
++number
: number
becomes 6 and the expression evaluates to 6number
Pre increment increments the value and returns the incremented result. Post increment returns the value before the increment, then increments the variable.
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