C++ Function Call by Reference PDF
C++ Function Call by Reference PDF
C++functioncallbyreference
Searchthissite...
Home
Programming
Java
Web
Databases
C++functioncallbyreference
ModernBabyNames
Advertisements
OnlinePhotoEditing
Advertisements
PreviousPage
C++Basics
C++Home
C++Overview
C++EnvironmentSetup
C++BasicSyntax
C++Comments
C++DataTypes
C++VariableTypes
C++VariableScope
C++Constants/Literals
C++ModifierTypes
C++StorageClasses
C++Operators
C++LoopTypes
C++DecisionMaking
C++Functions
C++Numbers
C++Arrays
C++Strings
C++Pointers
C++References
C++Date&Time
C++BasicInput/Output
C++DataStructures
C++ObjectOriented
C++Classes&Objects
C++Inheritance
C++Overloading
NextPage
Thecallbyreferencemethodofpassingargumentstoafunctioncopiesthereferenceofanargument
intotheformalparameter.Insidethefunction,thereferenceisusedtoaccesstheactualargumentused
inthecall.Thismeansthatchangesmadetotheparameteraffectthepassedargument.
Topassthevaluebyreference,argumentreferenceispassedtothefunctionsjustlikeanyothervalue.
So accordingly you need to declare the function parameters as reference types as in the following
functionswap(),whichexchangesthevaluesofthetwointegervariablespointedtobyitsarguments.
//functiondefinitiontoswapthevalues.
voidswap(int&x,int&y)
{
inttemp;
temp=x;/*savethevalueataddressx*/
x=y;/*putyintox*/
y=temp;/*putxintoy*/
return;
}
Fornow,letuscallthefunctionswap()bypassingvaluesbyreferenceasinthefollowingexample:
#include<iostream>
usingnamespacestd;
//functiondeclaration
voidswap(int&x,int&y);
intmain()
{
//localvariabledeclaration:
inta=100;
intb=200;
cout<<"Beforeswap,valueofa:"<<a<<endl;
cout<<"Beforeswap,valueofb:"<<b<<endl;
/*callingafunctiontoswapthevaluesusingvariablereference.*/
swap(a,b);
cout<<"Afterswap,valueofa:"<<a<<endl;
cout<<"Afterswap,valueofb:"<<b<<endl;
return0;
}
Whentheabovecodeisputtogetherinafile,compiledandexecuted,itproducesthefollowingresult:
Beforeswap,valueofa:100
Beforeswap,valueofb:200
Afterswap,valueofa:200
Afterswap,valueofb:100
C++Polymorphism
C++Abstraction
C++Encapsulation
C++Interfaces
C++Advanced
C++FilesandStreams
C++ExceptionHandling
C++DynamicMemory
C++Namespaces
C++Templates
PreviousPage
PrintVersion
PDFVersion
NextPage
Advertisements
ASP.NETAJAX
DevTools
80+EasytoUseControls.
1200+Demos.Trustedby
10,000Developers
C++Preprocessor
C++SignalHandling
C++Multithreading
C++WebProgramming
C++UsefulResources
http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm
1/2
2/22/2015
C++functioncallbyreference
C++QuickGuide
C++STLTutorial
C++StandardLibrary
C++UsefulResources
SelectedReading
Developer'sBestPractices
EffectiveResumeWriting
ComputerGlossary
WhoisWho
ASP.NET | jQuery | AJAX | ANT | JSP | Servlets | log4j | iBATIS | Hibernate | JDBC | Struts | HTML5 | SQL | MySQL | C++ | UNIX
Copyright2014bytutorialspoint.AllRightsReserved.
http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm
2/2