Reputation: 2590
Consider this code :
int func1()
{
cout<<"Plus"<<endl;
return 1;
}
int func2()
{
cout<<"Multiplication"<<endl;
return 2;
}
int main()
{
cout<<func1()+4*func2();
}
According to this page * operator has higher precedence than + operator So I expect the result to be :
Multiplication
Plus
9
But the result is
Plus
Multipication
9
!! What is going on in compiler parser ?! Does compiler prefer Operator associaty ? Is the output same in all c/c++ compilers?
Upvotes: 1
Views: 419
Reputation: 133879
The compiler is free to evaluate functions in any order it pleases - the only cases within expressions where the order of evaluation is guaranteed are the sequence points; operators ||
, &&
, ,
, and ?
of the ternary conditional operator ? :
are sequence points. In each case the left side has all its values and side effects evaluated before the right side is touched.
Upvotes: 8
Reputation: 212949
Operator precedence is not the same thing as order of evaluation.
You have no guarantee about the order of evaluation - the compiler is free to call functions in whatever order it likes within an expression so long as you get the correct result.
(A minor qualification: anything which introduces a sequence point (which includes short circuit operators), will have an effect on order of evaluation, but there are no sequence points within the expression in this particular case.)
Upvotes: 27