-2

Lets take simple C++ code like:

int main(){
    int a = 0;
    while(a<3) {
        a=a++;
        std::cout<<a<<std::endl;
    }  
}

This code built using Visual Studio 2015 print 1, 2, 3 when g++ 5.2.0 goes into an infinite loop and print only zeros.

According to C++ Operator Precedence assignment operator (=) has a lower priority then a post-incrementation. It would suggest that first zero is assignment to variable 'a', after that 'a' is incremented, so after first iteration a = 1. So result obtained from VS 2015 is right. Why GCC produce different output?

1 Answers1

6

Your pogram is invalid (Undefined behavior) thus the compiler can generate anything.

The problem is your assigning to a single variable more than once in a statement (something to do with sequence points).

a=a++;

Thus should be:

 a++;
Martin York
  • 257,169
  • 86
  • 333
  • 562