Question

the following code:

myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue() << myQueue.dequeue();

prints "ba" to the console

while:

myQueue.enqueue('a');
myQueue.enqueue('b');
cout << myQueue.dequeue();
cout << myQueue.dequeue();

prints "ab" why is this?

It seems as though cout is calling the outermost (closest to the ;) function first and working its way in, is that the way it behaves?

Was it helpful?

Solution

There's no sequence point with the << operator so the compiler is free to evaluate either dequeue function first. What is guaranteed is that the result of the second dequeue call (in the order in which it appears in the expression and not necessarily the order in which it is evaluated) is <<'ed to the result of <<'ing the first (if you get what I'm saying).

So the compiler is free to translate your code into some thing like any of these (pseudo intermediate c++). This isn't intended to be an exhaustive list.

auto tmp2 = myQueue.dequeue();
auto tmp1 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
tmp3 << tmp2;

or

auto tmp1 = myQueue.dequeue();
auto tmp2 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
tmp3 << tmp2;

or

auto tmp1 = myQueue.dequeue();
std::ostream& tmp3 = cout << tmp1;
auto tmp2 = myQueue.dequeue();
tmp3 << tmp2;

Here's what the temporaries correspond to in the original expression.

cout << myQueue.dequeue() << myQueue.dequeue();
|       |               |    |               |
|       |____ tmp1 _____|    |_____ tmp2 ____|
|                       |
|________ tmp3 _________|

OTHER TIPS

The call from your example:

cout << myQueue.dequeue() << myQueue.dequeue();

translates to the following expression with two calls of operator<< function:

operator<<( operator<<( cout, myQueue.dequeue() ), myQueue.dequeue() );
-------------------- 1
---------2

The order of evaluation of cout, myQueue.dequeue() is unspecified. However, the order of operator<< function calls is well specified, as marked with 1 and 2

Since C++17 the behaviour of this code has changed; the left operand of << is sequenced before the right operand of <<, even when it is an overloaded operator. The output must now be ab.

For further reading see: What are the evaluation order guarantees introduced by C++17?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top