++*p: does this code sometimes work differently in cout? why?

foo1(){
int x=4;
int *p = &x;
cout << ++*p <<endl;
}

foo2(){
int x=4;
int *p = &x;
cout << *p++ << " " << ++*p << endl;
}

foo3(){
int x=4;
int *p = &x;
cout << *p << " " << *p++ << endl;
}

main(){
foo1();
foo2();
foo3();
}

I ran above code in VC++ 2008 and it printed:
5
5 -858993460
-858993460 4

foo1() and foo3() printed as i expected. But I don't understand why foo2() prints 5 -858993460?. Since ++*p is executed before
*p++ in foo2(), shouldn't it print as 5 5?
Can someone please clarify this for me?
Thanks in advance.

Last edited on
foo1() and foo3() printed as i expected. But I don't understand why foo2() prints 5 -858993460?. Since ++*p is executed before
*p++ in foo2(), shouldn't it print as 5 5?


I would say that this comes under the heading "undefined behaviour" - different compilers will give different output.
Last edited on
Note that *p++ is not the same as (*p)++, but *(p++). The same doesn't apply to ++*p, since both preincrement and dereference are unary operators.
Topic archived. No new replies allowed.