-2

During study in C++ at school, when we learn about operator ++ in C++, we know ++c and c++ are different.
When we test more about this with this kind of code:

#include <iostream>

using namespace std;

int main(){
    int c=10;
    cout<<++c<<" "<<c++<<endl;
    return 0;
}

Why did above code gave output of 12 and 10 in C++?
The computer (we tests with both cout and printf, we also tried VC++ and g++) give this to me:

12 10

Both "cout" and "printf" gave the same result.
But when we test in calculation, the result is all right.

#include <iostream>

using namespace std;

int main(){
    int c=10;
    int r=++c^c++;
    cout<<r<<endl;
    return 0;
}

Above source code gave me 0 which means while above XOR operation executing, both left hand side (++c) and right hand side (c++) giving the same value to XOR operator which is 11 (We get the value 11 by replacing c++ with 11 and computer gives the same result 0).

This is really wired. Did anyone noticed this?

By the way, we test in both debug mode and release mode in both Windows and Lubuntu. So we think this is relating to the standard library. But we aren't expecting that we can read the stdlib as a NOOB. So hoping someone can find a reason or solution.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

1

The code int r=++c^c++; is undefined behaviour and should not be used, not ever. You can't modify the variable twice before sequence point.

SergeyA
  • 61,605
  • 5
  • 78
  • 137