c++c++17operatorsoperator-precedence

Confusion about operator precedence in C++


I'm learning C++ and am currently learning about operator precedence. I'm playing with the following examples.

Imagine each piece as distinct pieces of code run at separate times, not multiple code blocks within the same method.

int b = 4;
int result = ++b;

// In the above example the result will be 5, as expected.
int b = 4;
int result = ++b + b;

// Here the result will be 10 as expected.
int b = 4;
int result = ++b + ++b;

Here the result is 12. I don't understand why. Shouldn't the compiler evaluate ++b changing 4 to 5, then ++b changing 5 to 6, resulting in 5+6 = 11?


Solution

  • It's undefined behaviour, violating sequence rules.

    Between the previous and next sequence points a scalar object must have its stored value modified at most once by the evaluation of an expression, otherwise the behavior is undefined.

    int b = 4;
    int result = ++b + ++b;