Pointers and Reference Variables

A reference variable can be view as a constant pointer to a variable. A reference variable must be initialized in its declaration as a reference to a particular variable, and this  reference variable could not be changed

Which means that reference variable cannot be null.


Considering the following declarations:



int i = 10, *p = &j, &r = i;


variable p is of type int*, this means a pointer to an integer, meanwhile r is of type int&, an integer reference variable. As already stated, a reference variable must be initialized to a particular variable during declaration. In the above declarations a reference variable r can be considered a synonym of variable i or to be more logic a reference variable r can be considered a different name for a variable i in this case whatever changes in i will also change r.

With above declarations, the output result will be 10 10 10. 


Let see in code:

#include <iostream>
#include <string>

using namespace std;


int main()
{

int i = 10, *p , &r = i; // declarations of int, pointers and reference variables
p = &i;

printf("Value of i is %d\n", i);
printf("Value of pointer to an integer is %d\n", *p);
printf("Value of reference variable r is %d\n", r);
}


Outputs




Value of i is 10

Value of pointer to an integer is 10

Value of reference variable r is 10



Thus means that without dereferencing of reference variables we could accomplished same result that we can accomplish with dereferencing of pointer variables. in a nutshell since reference variable are implemented as constant pointers we can change declaration from:


int& r = n;


to 


int *const r = &n;


here r indicates a constant pointer to integer.


Note:

Reference variables are used in passing arguments by reference to function calls.

Used call-by-value to pass arguments to a function unless the caller explicitly requires called function to modify the value of the argument variable in the caller's environment. This prevents accidental modification of the caller's arguments and is another example of the priniciple of priviledge. 

Call by reference must  be use to modify mutiple values in a calling function.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

New Post

New style string formatting in Python

In this section, you will learn the usage of the new style formatting. Learn more here . Python 3 introduced a new way to do string formatti...