Posted By:
3 Jul, 2013 12:57 pm PDT

Call by reference in C++

  • We know that call by reference is the term used in functions.
  • But what do you mean by call by reference?
Attachment:None


Call By Reference

When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

For example:

//swapping of two numbers

#include<iostream.h>

void swap(int &a, int &b)

{

int temp;

temp=*a;

*a=*b;

*b=temp;

cout<<”\nIn function:

cout<<*a<<”\t”<<*b;

}

void main()

{

int x,y;

x=5;y=3;

swap(&x,&y);

cout<<”\nIn main”;

cout<<x<<”\t”<<y;

}

 

OUTPUT of the above code is:

In function: 3   5

In main: 3     5

 

Explanation:

In the main(), address of variables x,y are sent as arguments to the function ‘swap’. As swap() has the access to the address of the arguments, manipulation of passed arguments inside swap() would be directly reflected in the values of x,y.

 

Was it useful?  




Please login to reply to this problem.