问题
Possible Duplicate:
Unexpected order of evaluation (compiler bug?)
I couldn't predict the output for this program :
#include<iostream>
using namespace std;
int *p(int *a)
{
(*a)++;
return a;
}
int main()
{
int i=0;
cout<<i++<<" "<<(*p(&i))++<<" "<<i++<<" "<<i<<endl;
return 0;
}
When compiled in vs2008, it outputs 3 2 0 4
. Can anybody explain why it's not 0 2 3 4
?
Note: It works great if there is no function call to p
.
Thanks in advance!
回答1:
Undefined behaviour. Could do anything.
See this answer for a good explanation.
回答2:
The point isn't cout's precedence, but the ++ operator.
This operator's side effect can take place any time between two sequence points, which means anywhere in the statemenet, in this case. The exact order it happens is, as @oli-charlesworth says, undefined.
cout's precedence is left to right, so the leftmost is printed first. But the value of each number depends on the behavior of ++.
来源:https://stackoverflow.com/questions/8704455/how-does-couts-operator-work-with-regard-to-operator-precedence