1.

Explain with example by passing the reference.

Answer»

#include <iostream>
// function declaration
void swap(int& x, int& y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout<< “Before swap, value of a << a << endl;
cout << “Before swap, value of b << b << endl;
/* calling a function to swap the values.*/

swap(a, b);
cout<< “After swap, value of a << a << endl;
cout << “After swap, value of b << b << endl;
}
// function definition to swap the values.
void swap(int& x, int& y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}

The output of the above program is:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

In C++, reference variables are possible and works like alias to original memory locations. In the above program, the function void swap(int& x, int& y); is declared with two arguments with x and y as reference variables. During the function call swap() takes two arguments (formal arguments) ‘x’ and ‘y’ which are reference variables to variables of actual arguments ‘a’ and ‘b’ respectively. The interchange of value takes place between x and y in the body of swap() function. Here, variable ‘x’ and ‘y’ are used to manipulate the data values from the location ‘a’ and ‘b’ directly.



Discussion

No Comment Found