virgil_van_maguire's blog

By virgil_van_maguire, history, 22 months ago, In English

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;
  • Vote: I like it
  • +11
  • Vote: I do not like it

| Write comment?
»
22 months ago, hide # |
← Rev. 6  
Vote: I like it +4 Vote: I do not like it

x++ + ++x=12

++x + x++=12

++x + ++x=13

++x + ++x + ++x=21

»
22 months ago, hide # |
 
Vote: I like it +2 Vote: I do not like it
first one:
second one:
third one:
fourth:
»
22 months ago, hide # |
 
Vote: I like it +62 Vote: I do not like it

caw caw caw

»
22 months ago, hide # |
← Rev. 2  
Vote: I like it +48 Vote: I do not like it

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 under x, so does x++ and CPU instructions can be arranged in any way because standard not require which increment goes first.

Every cout there is UB.

»
22 months ago, hide # |
← Rev. 2  
Vote: I like it +42 Vote: I do not like it

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).

»
22 months ago, hide # |
← Rev. 2  
Vote: I like it +4 Vote: I do not like it

cool quiz now guess what this will output without compiling

    int x=5;
    cout<<x+++x<<endl;
»
22 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

It`s so beautiful!