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
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++