0

Again, a silly question.

#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
 int i = 0;
 i = i++;
 cout<<i;

 return 0;
}

I get 1 printed as a result of this program though I expected 0: first a temp object created eing equal 0, then i is incremented, then temp object is returned and assigned to i. Just according to:

5.2.6 Increment and decrement [expr.post.incr] 1 The value obtained by applying a postfix ++ is the value that the operand had before applying the operator. [Note: the value obtained is a copy of the original value ]

I checked it under MS VC 2008 and GCC. They give both the same result, though at least gcc issues a warning in incrementation string. Where am I wrong?

Mat
  • 202,337
  • 40
  • 393
  • 406
flashnik
  • 1,900
  • 4
  • 19
  • 38

1 Answers1

0

The behavior of

i = i++;

is undefined. If a single expression assigns two different values to a variable, the C++ spec says that anything can happen - it could take on its old value, one of the two new values, or pretty much anything at all. The reason for this is that it allows the compiler to make much more aggressive optimizations of simple expressions. The compiler could rearrange the order in which the assignment and ++ are executed, for example, if it thought it were more efficient.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Could you please provide a proof link to the standard, why it is undefined? I guessed so but haven't found a proof. And only GCC provides warning in `-Wall` mode. – flashnik Jan 08 '11 at 23:43
  • The result is the same even without optimizations and in debug mode. – flashnik Jan 08 '11 at 23:48
  • 3
    http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points/4176333#4176333 – Yakov Galka Jan 08 '11 at 23:48
  • 1
    @flashnik ISO/IEC 14882:2003 §5 (4): 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. – Oswald Jan 08 '11 at 23:51