Operator << in i/o streams

Today I met some difficulty in operator << when learning the Standard Library, as follows.


Operator << is evaluated from left to right,so the expression
std::cout << x << y
would print x first and the next is y.


But the next code

int f(int& x) {
++x;
return -1;
}

int i = 0;
std::cout << i << " " << f(i) << " " << i << std::endl;

would print
1 -1 0
which meant that the implementation prints the result from right to left.


But the expression
std::cout << std::setw(12) << std::setfill('_') << std::right << "abcd" << std::endl
prints
________abcd
which meant that it surely printed from left to right.


Why?

So sorry I used the forum the first time, I didn't know how to use the format when i edited the topic, so the content is very chaotic, I'm really so sorry.
Last edited on
Order of evaluation:
Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.

There are several exceptions to this rule (e.g. for the &&, ||, and , operators) which are noted below.

Otherwise, there is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression f1() + f2() + f3() is parsed as (f1() + f2()) + f3() due to left-to-right associativity of operator+, but the function call to f3 may be evaluated first, last, or between f1() or f2() at run time.
http://en.cppreference.com/w/cpp/language/eval_order


Read the whole page; in particular the section 'Undefined behaviour'

How to use code tags: http://www.cplusplus.com/articles/jEywvCM9/
Topic archived. No new replies allowed.