-3

Possible Duplicate:
is i=i++ truly a undefined behavior?

i just want too explain ++ and -- to my students and show them some code about them in visual studio 2010 I just test this code on it

int main(){
   int a=3;
   int b=3;
   a=a++;
   cout<<a<<endl;
   cout<<b++<<endl;
}

I expect that both of cout print 3 but the first cout print 4!!!! I test it in g++ and both of couts print 3... what's wrong???

Community
  • 1
  • 1
pooya
  • 901
  • 2
  • 15
  • 29

4 Answers4

7

The behavior of a=a++ is undefined. If you'd like to increment a, use a++ instead.

Phonon
  • 12,549
  • 13
  • 64
  • 114
4

http://www.slideshare.net/olvemaudal/deep-c

Read about sequence points.

emesx
  • 12,555
  • 10
  • 58
  • 91
1

a=a++; is not well defined. Don't use it.

Dan
  • 10,531
  • 2
  • 36
  • 55
1

You are only allowed do one assignment within one sequence point in C++ IIRC. So this is undefined. The following presentation discusses this issue in deep http://www.slideshare.net/olvemaudal/deep-c .

Nils
  • 13,319
  • 19
  • 86
  • 108