-2

If the order of evaluation of sub expressions is not guaranteed, then why is this correct?

int a = 1;
a = a + 1;

Here the compiler could evaluate first a and then a + 1 so a can be 1 or 2 while this is not:

a = a++;

Here the compiler could evaluate first a and then a++ son a can be 1 or 2.

What's the difference?

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
xdevel2000
  • 20,780
  • 41
  • 129
  • 196

2 Answers2

1

It is undefined behavior. The reason follows::

The Standard in ยง5/4 says

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

and

The prior value shall be accessed only to determine the value to be stored.

It means, that between two sequence points a variable must not be modified more than once and, if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

Read about sequence points here , basically you have 2 assignments between 2 sequence points and that will cause undefined behavior.

a++ will increment value for a and then assign it to a and another assignment will be done by = operator, while a + 1 will not change value for a and you will have only 1 assignment between 2 sequence points

Community
  • 1
  • 1
LZR
  • 948
  • 10
  • 28