?
Solved

cout << operator associativity

Posted on 2013-10-23
8
Medium Priority
?
418 Views
Last Modified: 2013-11-19
All the sources that I have seen say that << operator in cout uses left to right associativity.  But this it doesn't explain the following example.

#include <iostream>
using namespace std;
class A {
public:
	A() { a[0] = 1; a[1] = 0; }
	int a[2];
	int b(void) { int x=a[0]; a[0]=a[1];a[1]=x; return x; }
};
    
int main(void) {
	A a;
	a.b();
	cout << a.b() << endl; 
		cout << a.a[1] << endl;
	return 0;
}

Open in new window


Output is only explained if it is evaluated right to left.

So I made another example and used debugger to see the execution.

#include <iostream>

using namespace std;

int f(int& x)
{
	x++;
    x *= x;
    return x;
}

int main(void)
{
    int a = 2, b=3;
    cout << f(a) << f(b) << endl;
    return 0;
}

Open in new window

I put a break point on function f and sure enough it called f(b) and then f(a).
Why?
0
Comment
Question by:farzanj
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 40

Accepted Solution

by:
Kyle Abrahams earned 400 total points
ID: 39594218
It boils down to the sequence order is not defined.

There's some great reading about this here:
stackoverflow.com/questions/1504752/c-output-evaluation-order-with-embedded-function-calls
0
 
LVL 31

Author Comment

by:farzanj
ID: 39594223
Sorry my example above incorrect.  Try this:

#include <iostream>
using namespace std;
class A {
public:
	A() { a[0] = 1; a[1] = 0; }
	int a[2];
	int b(void) { int x=a[0]; a[0]=a[1];a[1]=x; return x; }
};
    
int main(void) {
	A a;
	a.b();
	cout << a.b() << a.a[1] << endl;
	return 0;
}

Open in new window

0
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 400 total points
ID: 39594229
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 31

Author Comment

by:farzanj
ID: 39594239
I have tried Visual Studio and g++ (GCC) on Linux as well and both have the same output.  If the order is not defined, it is pretty consistent with the compilers.
0
 
LVL 35

Assisted Solution

by:sarabande
sarabande earned 200 total points
ID: 39594641
cout << f(a) << f(b) << endl;

Open in new window


the statement evaluates to

operator<<(operator<<(operator<<(cout, f(a)), f(b)), endl);

Open in new window


that means the arguments of the middle function call are operator<<(cout, f(a)) and f(b). VC compiler would pass the arguments from right to left regardless of the calling convention (see http://msdn.microsoft.com/en-us/library/vstudio/46t77ak2(v=vs.120).aspx) what also means they were evaluated in that order.

so, your observation that f(b) was evaluated before f(a) is true for vc compiler and probably true for most other compilers as well.

Sara
0
 
LVL 22

Assisted Solution

by:ambience
ambience earned 200 total points
ID: 39595429
The answer is what ged325 said:  "sequence order is not defined."

cout << f(a) << f(b) << endl;

is a single expression, and whereas the associativity of the operator is defined, the order of evaluation of functions, temporaries - in a single expression - is up to the compiler (implementation). Even if all compiler writer chose to evaluate in a specific order, it still remains undefined and some day a compiler may choose to do it differently and still not break any rules.

It is therefore bad practice to write code that relies on sequencing of a particular compiler.

Similar reasoning applies to this for example

func( f(a), f(b), f(c) )

There is no defined order in which f(X) would be evaluated.
0
 
LVL 29

Assisted Solution

by:pepr
pepr earned 200 total points
ID: 39596471
In other words, the a.b() is used as a member function for returning a value but with side effects. This is a general problem in any language that allows that.

If you want to be sure that the things are called in the right order, call them as commands outside the cout << ... << end; and assign the results to temporary variables. Then do output the content of the variables. Or design the dedicated member function that has no side effects.
0
 
LVL 31

Author Closing Comment

by:farzanj
ID: 39660422
Thank you guys and sorry for the delay.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Q&A with Course Creator, Mark Lassoff, on the importance of HTML5 in the career of a modern-day developer.
This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question