-3

I have the following code:

#include<iostream>
using namespace std;
 int main() 
{
 int x=3;
 cout<<x++<<++x<<x++<<++x<<endl;
return 0; 
}

the output should be 3557 but it is 6747. why???

Also:

#include<iostream>
using namespace std;
 int main() 
{
 int x=3;
    cout <<x++<<endl;
    cout<<++x<< endl;
    cout<<x++<< endl;
    cout<<++x<< endl;
return 0; 
}

The above code gives: 3 5 5 7 (every digit in new line) Can anyone explain why?

Farhan Javed
  • 413
  • 2
  • 5
  • 17

1 Answers1

0
 int x=3;
 cout<<x++<<++x<<x++<<++x<<endl;

This is undefined behavior, so you could easily get any result.

int x=3;
cout <<x++<<endl; // x = 3, post incremented to 4...
cout<<++x<< endl; // here x = 4 and preincremented to x = 5
cout<<x++<< endl; // x = 5 , postincremented to 6...
cout<<++x<< endl; // so here x = 6 but preincremented to 7

Undefined behavior and sequence points

unexpected output in cout and printf

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • You should add a link to [this answer](http://stackoverflow.com/a/4176333/2700399) for an explanation of the undefined behavior. – Bart van Nierop Mar 25 '14 at 15:42