I have a piece of code
#include<iostream>
using namespace std;
main()
{
int x=12;
int *p = &x;
Check in your debugger here what the value of p is. I bet it's not
0xfef30ee0, the value that gets output twice. I wouldn't be surprised
if the value is sizeof int* (probably 4 or 8) less than 0xfef30ee0.
cout<<endl<<p<<endl<<*p++<<endl;
The statement above is a series of calls to operator<< functions. It
is equivalent to
cout.operator<<(endl).operator<<(p).operator<<(endl).operator<<(*p+
+).operator<<(endl);
The compiler has to call the functions in the right order, but it is
allowed to evaluate the arguments to all those operator<< function
calls *before* it calls any of them and *in any order it likes*. In
your case it happens to have chosen to evaluate the argument to the
fourth call (*p++) *before* evaluating the argument to the second call
(p) so the value of p that is displayed by the call operator<<(p) is
the value *after incrementing*.
You can force the compiler to evaluate p before evaluting *p++ by
putting the evaluations in separate statements. Change the one
statement above to
cout<<endl<<p<<endl;
cout<<*p++<<endl;
and run the program again. You should see the output you I think were
originally expecting.
cout<<endl<<p<<endl<<*p<<endl;
By the time we get to this statement, p has been incremented and
points to nowhere so the *p here has undefined behaviour. In practice,
the output you are seeing from this line is the value of p after
incrementing (which is also what the previous statement displayed),
followed by whatever your compiler happened to do in this case of
undefined behaviour.
}
but the output on G++ 3.4.2 compiler on linux is:
0xfef30ee0 //value of p (address of x)
12
0xfef30ee0 // again the same value of p( after
increementing)
0 // value at p is changed this time
Gavin Deane