0

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.

  • Does this answer your question? [Undefined behavior in c/c++: i++ + ++i vs ++i + i++](https://stackoverflow.com/questions/39900469/undefined-behavior-in-c-c-i-i-vs-i-i). This line `b= ++a + ++a;` invokes [undefined behavior](https://en.cppreference.com/w/cpp/language/ub), which means anything is allowed to happen, so it is rather pointless to speculate why anything in particular would happen. – dxiv Feb 21 '21 at 00:03
  • As a wise old Chinese monk once said... “undefined behaviour is undefined” – Mike Vine Feb 21 '21 at 00:06
  • oh i'm really sorry I didn't know this results in undefined behavior. thank you – costheta_z Feb 21 '21 at 00:08

0 Answers0