Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 643
Khaledvic Avatar asked Jan 23 '26 12:01

Khaledvic


1 Answers

Undefined behaviour. Could do anything.

See this answer for a good explanation.

like image 162
Oliver Charlesworth Avatar answered Jan 26 '26 01:01

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!