2

I'm learning c++ and 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?

Elliott
  • 2,603
  • 2
  • 18
  • 35
Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59

1 Answers1

3

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;
Elliott
  • 2,603
  • 2
  • 18
  • 35
User
  • 572
  • 2
  • 10
  • The term “sequence point” hasn’t been used since C++03, but you’re right that it’s undefined behavior. – Davis Herring Jul 23 '21 at 05:23
  • 1
    @Elliott the term was replaced with sequencing after C++11 – User Jul 23 '21 at 06:09
  • 1
    Is this still an issue in c++17? I'll have to read more on undefined behavior. I don't get why it would randomly choose 12, and deterministically choose that. It should be 11 no? Also can you explain what a sequence point is? – Jeremy Fisher Jul 23 '21 at 19:41
  • 1
    yes, yes surely you should there is already a lot of material available e.g [refer this](https://en.cppreference.com/w/cpp/language/eval_order#:~:text=The%20compiler%20can%20evaluate%20operands,same%20expression%20is%20evaluated%20again.). In other languages can be but C++ don't have any definative behaviour for this. I can surely but there is already lot of explanations available for e.g [sequence point](https://stackoverflow.com/questions/3575350/sequence-points-in-c) , I will be repeating what's already there . – User Jul 24 '21 at 09:17
  • 1
    @JeremyFisher the result is due to: increment b; increment b; add b to b giving result. It's not 'random', This order of operations is implicitly permitted by the sequencing rules, since the expression has undefined behaviour. – iggy Jul 24 '21 at 11:53