I found unexpected output of following program.
Here pointer ptr point to address of variable i and i hold the value 10. It means the value of ptr also 10. Next ptr increment once. It means now it hold value 11. But in the following program ptr prints 12.
#include <iostream>
using namespace std;
int main()
{
int i = 10;
int *ptr = &i;
int j = 2;
j += *ptr++;
cout<<"i : "<<i<<"\n";
cout<<"j : "<<j<<"\n";
cout<<"ptr : "<<*ptr<<"\n";
}
Output:
i : 10
j : 12
ptr : 12
So I don't understand why ptr prints 12 instead of 11?
The program has undefined behavior.
This statement
j += *ptr++;
is equivalent to
j += *( ptr++ );
So the pointer now points to after the variable i that is it does not point to a valid object.
Thus this statement
cout<<"ptr : "<<*ptr<<"\n";
invokes undefined behavior.
It happened such a way that the compiler placed the variable j after the variable i. However the order of the variables is unspecified by the C++ Standard.
For example the gcc compiler's output is the same as you showed.
i : 10
j : 12
ptr : 12
While the clang compiler's output is
i : 10
j : 12
ptr : 4201824
What you mean is the following
j += ( *ptr )++;
In this case the output will be
i : 11
j : 12
ptr : 11
Pay attention to that the outputted value of i is 11 because the variable i is outputted in the following sentence when the side effect was already applied to the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With