guess the value of each of the following and explain your logic. (please don't run it, have fun guessing)
int x=5;
cout<< x++ + ++x<<endl;
x=5;
cout<< ++x + x++<<endl;
x=5;
cout<<++x + ++x<<endl;
x=5;
cout<<++x + ++x + ++x<<endl;
x++ + ++x=12
++x + x++=12
++x + ++x=13
++x + ++x + ++x=21
thanks for Rev. 2 without it i would've never understood.
How did you evaluate them to these values? can you please explain?
x++ will return 5 and make it 6, ++x will make it 7 then return 7, so it should be 5+7 = 12
should be the same thing? ++x will return 6 and make x=6, x++ will return 6 and make x=7, so 6+6 = 12
++x will return 6, 2nd one will return 7, so 6+7 = 13
6 + 7 + 8 = 21
caw caw caw
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4950.pdf
6.9.1.10
If a side effect on a memory location (6.7.1) is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent (6.9.2), the behavior is undefined.
Meaning:
x++
changes memory state underx
, so doesx++
and CPU instructions can be arranged in any way because standard not require which increment goes first.Every cout there is UB.
All of these are undefined behaviour, because the increment operations are unsequenced with respect to each other, and therefore could happen in any order or even at the same time (that is, if this wasn't defined as undefined behaviour by the C++ standard; given that it is, it may output whatever it wants).
The answer lies in the name of the operator.
++x
: Pre-increment (increment has high priority)x++
: Post-increment (increment has low priority)cout << x++;
: First print x then incrementcout << ++x;
: First increment then printCase 1 :
cout << x++ + ++x;
Case 2 :
cout << ++x + x++;
Case 3 :
cout << ++x + ++x;
Case 4 :
cout << ++x + ++x + ++x;
These results are based on the assumption of left-to-right evaluation and no reordering. However, in C++, modifying and accessing a variable multiple times in the same statement can invoke
undefined behavior
, so the actual result might vary depending on the compiler.cool quiz now guess what this will output without compiling
12
12
13
21
++x => Increases then prints
x++ => prints then Increases
when it x++ + ++x => he print it and increase + another increase then print
1st:5+7=12 2nd:6+6=12 3rd:6+7=13 4th:6+7+8=21
Output would be:
12
12
13
21
It`s so beautiful!