Call by reference in C++ Functions

By: Babbar Ankit  

Apart from the method discussed in the first tutorial (highlighing the use of pointer arguments) , C++ provides the \'&\'(referential) operator for calling by reference.

Syntax

function prototype
return-type function-name(data-type & arguement_name);
function definition

return-type function-name(data-type & arguement_name)

{

inside the body , the aguement is to be used as any other variable(not as pointer variable)

}
function call

function_name(arguement name);

//the variable is passed like any other variable of its data type and as an address

Example :: SWAP program revisited

#include<iostream>
using namespace std;

void swap_ref(int &a,int &b);
void swap_val(int a,int b);

 int main()
{
int a=3,b=6;
printf(“\\na=%d  b=%d”,a,b);
swap_val(a,b);

printf(“\\na=%d  b=%d”,a,b);
swap_ref(a,b);
printf(“\\n a=%d  b=%d”,a,b);

return 1;
}

void swap_ref(int &a, int &b)
{
//function acceptsa reference
a=a+b;
//to original parameter variable
b=a-b;
a=a-b;
}
void swap_val(int a, int b)
{
a=a+b;
b=a-b;
a=a-b;
}

OUTPUT:
a=3  b=6
a=3  b=6
a=6  b=3

Authors Url: http://www.botskool.com/programming-tutorials




Archived Comments

1. @Hot Water Systems:
why do you think that replacing two ampersands with 10-12 asterisks would

View Tutorial          By: Nikhil at 2012-11-12 04:50:55

2. thank u very much to provide it,

but should be in c++ format.....

View Tutorial          By: rohit at 2011-09-26 07:09:33

3. example is good but in c++ we can't use printf().
View Tutorial          By: vikas at 2009-10-26 20:12:08

4. but it will be very simple if we use pointer in it.
View Tutorial          By: Hot Water Systems at 2009-06-01 03:51:48


Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial