Link to home
Start Free TrialLog in
Avatar of farzanj
farzanjFlag for Canada

asked on

cout << operator associativity

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?
ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of farzanj

ASKER

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

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of farzanj

ASKER

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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of farzanj

ASKER

Thank you guys and sorry for the delay.