The fundamental reason behind this difference in processing order is operator precedence1.
Precedence and associativity determine how the operands are grouped in an expression.
So there are 2 important points to keep in mind here:
- Operands of operators with higher precedence group more tightly than
operands of operators at lower precedence.
- Associativity determines how to group operands with the same precedence.
Lets consider some examples to clear this up.
Example 1
Consider the expression 3+4*5+2
.
Now the value(result) of this expression depends upon how the subexpressions are grouped.
In this example, multiplication and division have the same precedence as each other but they have higher precedence than addition. Thus, using Point 1 above, operands to muliplication and division group before operands to addition.
Also, the arithmetic operators are left associative which means operands of operators at the same precedence group left to right. This is what associativity meant in point 2 above.
Now, using these two facts the expression 3+4*5+2
is equivalent to:
((3+(4*5))+2)
which will result in a value of 25
.
Example 2
Consider the expression cin >> x >> y;
In this example, the IO operators are left associative which means they group left to right. This is why we are able to combine IO operations in a single expression as above. This also means that the above expression is equivalent to writing:
((std::cin >> x) >> y);
Example 3
Lets come back to your example expression cout << string_1 << string_2 << string_3
As i said in example 2, IO operators are left associative which means they group left to right. Again, this means the above expression is equivalent to writing:
(((cout << string_1) << string_2) << string_3)
Example 4
Consider the expression a = b = 5
In this case, the assignment operator is right associative which means they group right to left. Thus the above expression is equivalent to writing:
(a = (b = 5))
This means 2 things:
- the rightmost assignment
b = 5
is the operand of the leftmost assignment operator.
- because assignment returns its left-hand operand, the result of the rightmost assignment(which will be
b
in this case) is assigned to a
.
1 Precedence specifies how the operands are grouped. It says nothing about the order
in which the operands are evaluated. There is no concept of left-to-right or right-to-left evaluation in C++.