Solved

cout << operator associativity

Posted on 2013-10-23
8
411 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 100 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 100 total points
ID: 39594229
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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 34

Assisted Solution

by:sarabande
sarabande earned 50 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 50 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 50 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

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!

Question has a verified solution.

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

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

623 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