How does cout's << operator work with regard to operator precedence? [duplicate]

余生长醉 提交于 2019-12-23 16:06:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!