Reputation: 5106
This is the C++
code:
#include<iostream>
using namespace std;
int a=8;
int fun(int &a)
{
a=a*a;
return a;
}
int main()
{
cout << a << endl \
<< fun(a) << endl \
<< a << endl;
return 0;
}
why does it output:
64 64 8
the <<
operator's associativity is left to right, so why not output 8 64 64
?
Does it have the relation to the sequence point and the effect side?
Upvotes: 14
Views: 609
Reputation: 185852
Associativity and evaluation order are not the same thing. The expression a << b << c
is equivalent to (a << b) << c
due to left-to-right associativity, but when it comes to evaluation order, the compiler is free to evaluate c
first then a << b
and, likewise, it can evaluate b
before it evaluates a
. In fact, it can even evaluate the terms in the order b
→ c
→ a
if it wants, and it just might if it concludes that such an order will maximise performance by minimising pipeline stalls, cache misses, etc.
Upvotes: 24