Suppose following piece of code:
#include <iostream>
using namespace std;
char one()
{
cout << "one\n";
return '1';
}
char two()
{
cout << "two\n";
return '2';
}
int main(int,char**)
{
// 1:
cout << one()
<< '\n'
<< two()
<< '\n';
// 2:
operator<<(
operator<<(
operator<<(
operator<<(
cout,
one()),
'\n'),
two()),
'\n');
}
execution of lines marked as 1
and 2
, being compiled with ideone does the same, it prints following:
two
one
1
2
From my point of view, what we observe here is unspecified behaviour, as order in which function arguments are resolved is unspecified.
This was a question at an interview, printing above given sequence (without any alternatives) was supposed to be correct answer, but is it really correct?
You are correct, and the interviewer shows a frighteningly common lack of understanding about the language and its rules.
Those two lines are strictly equivalent, iff every
operator<<
called for the first line is always a free function (The standard says they are).As you rightly thought, the ordering between the function-calls, except where ones arguments are the return-value of another, are indeterminately sequenced (before or after, but unspecified which):
Naming all the parts:
Ordering constraints:
Or a different representation:
Thus, all valid full orders: