Program 1:
#include <iostream>
using namespace std;
int main(){
int x=5;
int* xd=&x;
cout<<*xd<<endl;
(*xd) ;
cout<<*xd;
}
output is 5 and 6 .
Program 2:
#include<iostream>
using namespace std;
int main(){
int x=5;
int* xd=&x;
cout<<*xd<<endl;
*xd ;
cout<<*xd;
}
Output is 5 and some random number rather than 6.
CodePudding user response:
The second code uses *xd ;
which is equivalent to *(xd );
due to operator precedence. In other words, the postfix operator
has higher precedence than operator *
used for indirection and thus by writing *xd
you're incrementing the pointer xd
and then dereferencing that incremented pointer in the next statement cout<<*xd;
which leads to undefined behavior.
cout<<*xd;//undefined behavior as this dereferences the incremented pointer
While the first code is well-formed because in code 1, you're first dereferencing the pointer xd
and then incrementing that result(which is an int
) which is totally fine.
(*xd) ; //valid as you've surrounded xd with parenthesis () and thus you're incrementing x instead of xd
cout<<*xd;//valid as `xd` still points to `x`
CodePudding user response:
For the first lines of code you wrote :
int main(){
int x=5; // Here x is equal to 5
int* xd=&x; // You declare a pointer xd that points on the value of x
cout<<*xd<<endl; // The value of xd is 5.
(*xd) ; // The value of 5 1 which is equal to 6
cout<<*xd; // Print out 6
As for the second code
include using namespace std;
int main(){
int x=5; // Here x is equal to 5
int* xd=&x; // You declare a pointer xd that points on the value of x
cout<<*xd<<endl; // The value of xd is 5.
*xd ; // increment the value of the pointer address by 1
cout<<*xd; // Display a random pointer address
}
To understand more, you should learn about the pointer address and the pointer value Doing (*xd) will increment the value of your pointer. As for *xd will increment a random value that your pointer address is pointing on.
CodePudding user response:
In the first example, the increment operator is being performed on the dereferenced value of xd (i.e. 5 1).
In the second example, the incprement operator is being performed on the pointer to the memory address where 5 is held, i.e. moving the pointer to after the value (which is not initialized)