-1

Why do we get different results for the two follow statements:

int x = 5;
x = x * x++;

the output is 26; whereas the next example returns 30, though they are same?!

int x = 5;
x *= x++;

Thank you

Abdulkarim Kanaan
  • 1,703
  • 4
  • 20
  • 32

2 Answers2

4

These both exhibit undefined behaviour in both C++03 and C++11. In C++11 terminology, you can't have two unsequenced modifications of the same scalar or a modification and a value computation using the same scalar, otherwise you have undefined behaviour.

x = x * x++;

In this case, incrementing x (a modification) is unsequenced with the other two value computation of x.

x *= x++;

In this case, incrementing x is unsequenced with the value computation of x on the left.

For the meaning of undefined behaviour, see C++11 §1.3.24:

undefined behavior
behavior for which this International Standard imposes no requirements

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    *"incrementing `x` is unsequenced"* that is, the modification of `x` is unsequenced to the other two value computations. (It is sequenced after the value computation of the `x++`.) – dyp Jan 01 '14 at 22:33
  • I'm just wondering, what's the reasoning for undefined and not just unspecified evaluation order? – user2345215 Jan 01 '14 at 22:33
  • @user2345215 I'm fairly sure it's to allow the compilers to perform optimizations under the assumption that the programmer doesn't do this. Somebody else might have a better answer though. – Joseph Mansfield Jan 01 '14 at 22:38
  • 2
    The compiler is supposed to let some operations run simultaneously (on different CPU cores). Hardware might do bizarre things (e.g. generate junk or throw an exception) when 2 cores read and write the same variable simultaneously. Since UB allows doing these things, compiler has much less to worry about when deciding how to do parallelization. – anatolyg Jan 01 '14 at 22:56
0

Assigning a ++'d value to the original value is undefined behavior. So it makes sense that assigning a ++'d then multiplied value is also undefined.

BWG
  • 2,238
  • 1
  • 20
  • 32