COnfused about printing order

Hi,
I just lost a few hours trying to make a program work because i was thinking it returned illogical values, because i printed them the wrong way

The code
 
std::cout<<function1()<<fucntion1()<<std::endl

printed "01", while the first call of the function returns true and the second call returns false (boolean return type)

Can anyone explain this to me? Is the text to output to cout evaluated from right to left, so the functions are executed in reverse order of their printing order?
cout << ... prints from left to right.

C++ gives no guarantee about the order of the two calls to function1().

If the order is important you can do something like this
1
2
3
bool val1 = function1();
bool val2 = function1();
std::cout << val1 << val2 << std::endl;
or
1
2
std::cout << function1();
std::cout << function1() << std::endl;
Ok. The order is not important, it was just debug messages. Good to know that the order is undefined.

An other question about cout order :
In function1, i printed something else with cout, and got the result

messsagefromInsideFunction1 messageFrominsideFunction1 0 1.

Can i deduce that cout prints the output only when it has fully evaluated the value of the cout line (else i would have had messsagefromInsideFunction1 0 messageFrominsideFunction1 1), or is it also something not guaranteed?
Well, let rewrite the expression in the functional form

std::cout<<function1()<<fucntion1()

std::cout.operator <<( function1() ).operator <<( function1() )

The order of evalution of sub-expressions in argument lists is undefined. Usually C/C++ compilers evaluates such sub-expressions from the right to the left according to the convention of passing arguments in the stack to C functions.
Last edited on
@bartoli
Can i deduce that cout prints the output only when it has fully evaluated the value of the cout line (else i would have had messsagefromInsideFunction1 0 messageFrominsideFunction1 1), or is it also something not guaranteed?


You can rewrite the original statement as two or even three statements

std::cout<<function1();
std::cout <<fucntion1();
std::cout << std::endl;
in addition to said by vlad from moscow
gcc usually evaluate right-to-left, clang — left-to-right (own experience). Other proofs:
http://stackoverflow.com/questions/15440833/g-vs-intel-clang-argument-passing-order

C++ standard 9.3.6p9:
The order of evaluation of function arguments is unspecified.
So do not do anything which depends on order of evaluation of function arguments (all operators boils down to function call).
Topic archived. No new replies allowed.