Reputation: 19
When I run this program I get strange output 1132. Can somebody explan me why is 1132?
//main.cpp
#include <iostream>
using namespace std;
int f1(int &a){return a++;}
int f2(int &a){return ++a;}
int main(){
int x, y;
int *px, *py;
x = 1;
y = 2;
px = &x;
py = &y;
cout << f1(*px) << *px << f2(*py) << *py << "\n";
return 0;
}
Upvotes: 1
Views: 140
Reputation: 69902
In this line:
cout << f1(*px) << *px << f2(*py) << *py << "\n";
The compiler is free to evaluate each expression in any order (even though the order of execution of operator<< is left to right).
The expressions are:
f1(*px)
f2(*py)
*px
*py
The evaluation order may be any one of the npr(4,4) permutations.
npr(4,4) = 4! / (4-4)! = 24
Do you feel lucky?
Upvotes: 1
Reputation: 5486
The order of evaluation in your case was right-to-left.
Note that there is no guarantee for a left-to-right evaluation.
So order was:
*py
f2(*py)
*px
f1(*px)
Only then the <<
operators ran (and were evaluated left-to-right as expected)
Upvotes: 2