Pointers with other operators
Pointer with different operators :
Pointer with Assignment operator :
We know that we can assign value of a simple variable into another variable by
using assignment operator ( = ) for e.g.
int a = 90 , b = 80 ;
By performing the activity given above you would find that all arrays declared in C++ are nothing but a const pointer having the addressof the first element of the same array.
b = a ; //The value of b is being replaced by the value of a i.e. 90
Similarly we can use assignment operator ( = ) between two pointer variables. So the following code snippet is very correct:
int x = 45 , y = 78 ; int * a = &x , *b = &y; a = b ; // assigning pointers to each other
When we write pointer a = b then the address which is being stored in b i,e a Hexadecimal value , gets copied into pointer a removing any of its previous contents (address).
Pointer with comparison operator (==)
Just like we use comparison operator (==) between two simple variables, we can also use it between two pointer variables.
What would be the output of the following code :
main ( ) { int a = 30 , b = 30 ; if ( a == b) cout<< “I Liked this study material”; else cout<< “Who has made it yaar!!”; }
Yes, you are absolutely right the output would be "I Liked this study material”, because the conditional expression a == b is evaluated to be true.
Now try to predict the output of the following code:
main( ) { int a = 30 , b = 30 ; int *p = &a ; int *q = &b ; if ( p == q) cout << “Kamal, Are you joking !”; else cout<< “Pointer is so easy following this study material”; }
If you are not able to find the answer yourself, execute the code and discuss with your teacher.
Note : Similarly we can also use != between two pointer variables.Sometimes we also compare a pointer variable with NULL or ‘\0’ to check whether it is pointing No where. |