Блог пользователя virgil_van_maguire

Автор virgil_van_maguire, история, 22 месяца назад, По-английски

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;
  • Проголосовать: нравится
  • +11
  • Проголосовать: не нравится

»
22 месяца назад, скрыть # |
← Rev. 6  
Проголосовать: нравится +4 Проголосовать: не нравится

x++ + ++x=12

++x + x++=12

++x + ++x=13

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

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится +2 Проголосовать: не нравится
first one:
second one:
third one:
fourth:
»
22 месяца назад, скрыть # |
 
Проголосовать: нравится +62 Проголосовать: не нравится

caw caw caw

»
22 месяца назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +48 Проголосовать: не нравится

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 месяца назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +42 Проголосовать: не нравится

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 месяца назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +4 Проголосовать: не нравится

cool quiz now guess what this will output without compiling

    int x=5;
    cout<<x+++x<<endl;
»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

It`s so beautiful!