How do we explain the result of the [removed]++x)+(++x)+(++x)?

后端 未结 5 1642
滥情空心
滥情空心 2020-11-28 13:05
x = 1;
std::cout << ((++x)+(++x)+(++x));

I expect the output to be 11, but it\'s actually 12. Why?

相关标签:
5条回答
  • 2020-11-28 13:18

    The code snippet will invoke Undefined behavior in both C/C++.Read about Sequence Point from here.

    0 讨论(0)
  • 2020-11-28 13:20

    In my opinion

    cout<<((++x)+(++x)+(++x));
    

    compiler first run prefix ++x so value of x becomes

    x=2


    now by ++x, x will become

    x=3


    after ++x

    x=4


    Now its time to add values of x

    x+x+x=4+4+4

    x+x+x=12

    0 讨论(0)
  • 2020-11-28 13:25

    This is actually undefined. C++ doesn't define explicitly the order of execution of a statement so it depends on the compiler and this syntax shouldn't be used.

    0 讨论(0)
  • 2020-11-28 13:35

    We explain it by expecting undefined behaviour rather than any particular result. As the expression attempts to modify x multiple times without an intervening sequence point its behaviour is undefined.

    0 讨论(0)
  • 2020-11-28 13:37

    As others have said, the C and C++ standards do not define the behaviour that this will produce.

    But for those people who don't see why the standards would do such a thing, let's go through a "real world" example:

    1 * 2 + 3 + 4 * 5
    

    There's nothing wrong with calculating 1 * 2 + 3 before we calculate 4*5. Just because multiplication has a higher precedence than addition doesn't mean we need to perform all multiplication in the expression before doing any addition. In fact there are many different orders you validly could perform your calculations.

    Where evaluations have side effects, different evaluation orders can affect the result. If the standard does not define the behaviour, do not rely on it.

    0 讨论(0)
提交回复
热议问题