commenting out cin at the end of the code changes output of previously used cout statement. Why is this happening? [duplicate]

  auto-increment, c++, cout

Something that I don’t understand happened today when I ran a simple C++ code as is pasted below:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int a=4,b;
    b= ++a + ++a;
    cout<<a<<" "<<b<<endl;
    //cin>>a;
}

The above code when executed gives an output

6 12

Whereas…

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int a=4,b;
    b= ++a + ++a;
    cout<<a<<" "<<b<<endl;
    cin>>a;
}

The above code when executed gives an output

6 11

The only difference in the codes in the cin>>a statement at the end… I was expecting both the codes to give output

6 11

Below is an image of the execution:

IMAGE

In the above image, the first output on the terminal corresponds to the code where the cin statement is commented out, and the second one with the cin statement present in the code.
Can someone explain this behavior please… Thank you.

Source: Windows Questions C++

LEAVE A COMMENT