Question

I was reading about the << operator in c++ from C++ Primer.
In it, there are some lines written about << operator

cout << "Some string" evaluates to a left hand ostream operator that is the result of the expression is cout object itself.(We say that operator associates left to right) .

It would be great it someone explains what is the meaning of the above mentioned lines.

Was it helpful?

Solution 2

Left to right associativity means that the expression is implicitly parenthesized like this:

(((cout << "foo") << "bar") << "baz")

In other words, the leftmost operation comes first.

By contrast, assignment is right-associative in most languages:

a = b = c + 5;

assigns c + 5 to both "a" and "b" because the assignment operator works from right-to-left.

OTHER TIPS

It means that

cout << a << b

is the same as

(cout << a) << b

not

cout << (a << b)

To clarify: the cout << a part outputs a, then returns cout, so the result of (cout << a) can be used as the left side to << b. Left-associativity just means if brackets could make the expression mean something else, assume brackets are set from left to right.

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