References and Pointers
Lets get straight to the code.....
(i)
int x = 2;
int *pInt = &x;
std::cout <<"The Value of *pInt is : "<< *pInt;
(O/P)
2
pInt is an integer pointer that points to the address of x
Hence *pInt points to the value contained in that address of x
(ii)
int x = 3
int &rInt = x;
rInt ++;
int *pp = &rInt;
cout<<"Value of rInt is :"<< rInt< cout<<"Value of *pp is :"<< *pp< cout<<"Address of rInt is :"<< &rInt< cout<<"Address of x is :"<< rInt<
(O/P)
rInt , *pp and x contain the same value
The address of rInt and x is also the same
rInt ++ increments the value in x
& to the left of = operator is taken as a reference
rInt is the reference to the integer x .
rInt contains the same value as x as its address is also the same as x
A reference is initialized only once
Hence upon incrementing rInt , the value in x is incremented.
*pp is an integer pointer that points to the value held in the address of rInt or x
(iii)
int a[N]; // The array name is always a pointer to the first element in the array
int *p = a; //*p points to the first element in array a
*p = 3; // Assigns 3 to the first element in a
*(p+1) = 3 // Also a valid statement
(iv)
References have to be intialized
int &r ; // invalid
extern int &r // This tells the compiler that the initialization of ref r is out of the scope
(v)
int &r = 1 ; // Error : lvalue needed
const int & r = 1 // Valid - the Lvalue is like an object whose values a variables unless specified.
This was a small gist on Pointers and References . I found it very useful for a quick glance.....
(i)
int x = 2;
int *pInt = &x;
std::cout <<"The Value of *pInt is : "<< *pInt;
(O/P)
2
pInt is an integer pointer that points to the address of x
Hence *pInt points to the value contained in that address of x
(ii)
int x = 3
int &rInt = x;
rInt ++;
int *pp = &rInt;
cout<<"Value of rInt is :"<< rInt<
(O/P)
rInt , *pp and x contain the same value
The address of rInt and x is also the same
rInt ++ increments the value in x
& to the left of = operator is taken as a reference
rInt is the reference to the integer x .
rInt contains the same value as x as its address is also the same as x
A reference is initialized only once
Hence upon incrementing rInt , the value in x is incremented.
*pp is an integer pointer that points to the value held in the address of rInt or x
(iii)
int a[N]; // The array name is always a pointer to the first element in the array
int *p = a; //*p points to the first element in array a
*p = 3; // Assigns 3 to the first element in a
*(p+1) = 3 // Also a valid statement
(iv)
References have to be intialized
int &r ; // invalid
extern int &r // This tells the compiler that the initialization of ref r is out of the scope
(v)
int &r = 1 ; // Error : lvalue needed
const int & r = 1 // Valid - the Lvalue is like an object whose values a variables unless specified.
This was a small gist on Pointers and References . I found it very useful for a quick glance.....
1 Comment