-3
#include <iostream>
using namespace std;

int main() {

    int x = 10;
    int y = 11;
    int z = 12;

    cout << x++ + --x + y++ - y-- + z;

    return 0;
}

The output here is 31

http://ideone.com/tp58av

The output usign Visual Studio 2005 is 30

What is wrong !

faressoft
  • 19,053
  • 44
  • 104
  • 146

1 Answers1

3
cout << x++ + --x + y++ - y-- + z;

This is undefined behavior.

You cannot access a single variable in a single sequence to both read and write to it multiple times.

As with all undefined behavior, it may work as you expect, it may reformat your hard drive, it may order me a pizza ... or it could start the self destruct sequence for the entire planet. All would be acceptable behavior as what you attempted to do is undefined.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • 1
    Blowing up the planet might break some laws, so I'm not sure you can call it "acceptable", but it would conform to the C++ standard. – Gort the Robot Nov 01 '13 at 18:52
  • "acceptable" in terms of the C++ standard. The human impact obviously would not be acceptable (except for nihilists). – Zac Howland Nov 01 '13 at 19:15