The output of the following code is "321" without quotes. Why not "123"?
#include <iostream>
using namespace std;
int& inc(int& start)
{
return ++start;
}
int main()
{
int i = 0;
cout << inc(i) << inc(i) << inc(i) << endl;
}
The output of the following code is "321" without quotes. Why not "123"?
#include <iostream>
using namespace std;
int& inc(int& start)
{
return ++start;
}
int main()
{
int i = 0;
cout << inc(i) << inc(i) << inc(i) << endl;
}
Your code invokes Unspecified Behaviour because the order of evaluation of the
arguments of operator<<
is unspecified
Calls to operator<<
modify the same variable. Don't write such code.
Note : Note that the code doesn't result in undefined behavior because there are sequence points (at least one function call) between when i
is modified and when it is read'.