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
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
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
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.