References:

References are similar to pointers in many aspects. In daily life sometimes we use reference for a person for example, son of Ibrahim, sister of John etc. likewise in C++ programming language we use references for variables. In other words reference is another name for a variable.

This variable is already defined or declared in the program. Programmers often mix pointers and references but a reference can never be NULL.

References are mostly used in object oriented programming. Unlike a pointer references cannot be changed to represent other variables.

 

Reference Declaration

The difference in declaring a reference and a simple variable is that & is used just after the data type of variable preceding the name of the variable.

SYNTAX: The syntax of declaring reference is as follows:

Data_type& reference_name = variable_name;

Where data type is the type of the reference, reference name is the name of reference and variable name is the name of the variable that is referenced.

EXAMPLE

Int var;

Int& rvar= var;

The ampersand (&) after the data type indicates the compiler that a reference has been declared.

 

Reference Initialization

The reference initialization is very simple. Initializing a reference means initializing the referenced variable.

EXAMPLE:

rvar=rvar + 10;

This example indicates that the value of the variable has been incremented by 10.It is mandatory to initialize a reference in its declaration.

C++ program functions can also be called using references.

 

Calling Functions by reference

The calling of functions by reference is done using formal parameters. Formal parameters are used in function header. They are used to receive values that are passed to the function in function call. To pass variables as references in a function just reference is used instead of the variable itself.

The following example demonstrates this concept:

# include<iostream>

Using namespace std;

{Void main()calling-functions-by-reference

int a;

a=1;

addition(a);

cout<<a;

}

Void addition(int& x)

{

x=x+1;

}

Working of the above program:

In the above example x is a reference of the variable ‘a’. The value of variable ‘a’ is initialized at 1. Then the function is called, the parameter of this function is a reference.

The value of this reference is incremented by 1 and now the value of the variable ‘a’ is 2. The control then returns to main() function and the value of ‘a’ is printed.