Saturday 4 April 2020

Reference Variables in C++



Reference Variables

A reference variable is a name that acts as an alternative name for a previously defined variable.  A reference variable is created as follows:

                        Data-type & reference-name = variable-name

Example:

                 float total = 100;
                 float & sum = total;

total is a float type variable that has already been declared; sum is the alternative name declared to represent the variable total.  Both the variables refer to the same data object in memory.  Now, the statements
                 cout << total;
and
                 cout<< sum;
Both variables will print the same value and if we change values, it will reflect in both the variables.
 A reference variable must be initialized the time of declaration. C++ also assigns additional meaning to the symbol &. Here, & is not an address operator.  The notation float & means reference to float.  Other examples are
   int n[10];
   int & x = n[10];   // x is alias for n[10]
   char & a =’\n’;    // initialize reference to a literal.
The variable x is an alternative to the array element n[10].  The variable a is initialized to the new-line constant.

No comments:

Post a Comment