Call by reference in C++ Functions

By: Babbar Ankit Viewed: 153239 times  Printer Friendly Format    


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



Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial