Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout << order of call to functions it prints?

Tags:

c++

cout

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?

like image 682
finiteloop Avatar asked Jan 24 '10 22:01

finiteloop


People also ask

Is print the same as cout?

cout is a reserved word. print is not, in c++. cout is the standard function to write something on the standard OUTput (screen, nowadays, printer before). Formely print, tells a programm to print on printer, cout on the screen.

Does cout print to terminal?

This article focuses on cout, which lets you print to the console but the general formatting described here is valid for all stream objects of type ostream. An ostream object is an instance of basic_ostream with the template parameter of type char.

Can we call a function in cout statement?

std::cout << f() << g(); The order of evaluation of the two function calls is unspecified; the compiler can call g() then f() , or it can call f() then g() . Same thing in your code; the compiler can squirrel away the value of a.a[0] the call a.b() , or it can call a.b() then grab the value of a.a[0] .


1 Answers

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 _________| 
like image 189
CB Bailey Avatar answered Sep 30 '22 04:09

CB Bailey