9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
csFundamentals.com
ProgrammingTutorialsandInterviewQuestions
Home
CProgramming
JavaProgramming
DataStructures
WebDevelopment
TechInterview
Whatisthedifferencebetweencallbyvalueandcallby
referenceinClanguage?
DifferencebetweenCallby
ValueandCallbyReference
ExampleusingCallbyValue
ExampleusingCallby
Reference
There are two ways to pass
arguments/parameters to
functioncallscallbyvalueand
call by reference. The major
difference between call by value
andcallbyreferenceisthatincall
by value a copy of actual
argumentsispassedtorespective
formal arguments. While, in call by reference the location (address) of actual
arguments is passed to formal arguments, hence any change made to formal
argumentswillalsoreflectinactualarguments.
In C, all function arguments are passed "by value" because C does not support
referenceslikeC++andJavado.InC,thecallingandcalledfunctionsdonotshare
anymemorytheyhavetheirowncopyandthecalledfunctioncannotdirectlyalter
avariableinthecallingfunctionitcanonlyalteritsprivate,temporarycopy.
Thecallbyvalueschemeisanasset,however,notaliability.Itusuallyleadstomore
compact programs with fewer extraneous variables, because parameters can be
treatedasconvenientlyinitializedlocalvariablesinthecalledroutine.Yet,thereare
somecaseswhereweneedcallbyreference:
1.Thecalledfunctioncommunicatestothecallingfunctiononlythroughreturn
statementandreturnstatementcanonlysendonlyonevaluebacktothecalling
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 1/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
function.Iftherearemorethanonevaluewewant Adsby Google
toalter,callbyreferenceisrequired
CProgramming
2.Ifthesizeofdataislarge,copyingactual
argumentstoformalargumentscouldbeatime CFunctionPointer
consumingoperationandoccupiesmorememory.
Thecallbyvaluedoesnotaddressabovecases,henceweneedcallbyreference.To
achievecallbyreferencefunctionalityinClanguagethecallingfunctionprovidesthe
addressofthevariabletobeset(technicallyapointertothevariable),andthecalled
function declares the parameter to be a pointer and access the variable indirectly
throughit.Sincetheaddressoftheargumentispassedtothefunction,codewithin
thecalledfunctioncanchangethevalueoftheactualarguments.
WhilestudyingcallbyvalueandcallbyreferenceinCitisimportanttonotethatthe
storyisdifferentforarrays.Whenthenameofanarrayisusedasanargument,the
valuepassedtothefunctionisthelocationoraddressofthebeginningofthearray
there is no copying of array elements. By subscripting this value, the function can
accessandalteranyelementoftheactualarray.
DifferencebetweenCallbyValueandCallbyReference
Differencebetweencallbyvalueandcallbyreference
callbyvalue callbyreference
In call by value, a copy of actual In call by reference, the location
arguments is passed to formal (address) of actual arguments is passed
argumentsofthecalledfunctionandany to formal arguments of the called
changemadetotheformalargumentsin function. This means by accessing the
thecalledfunctionhavenoeffectonthe addresses of actual arguments we can
valuesofactualargumentsinthecalling alter them within from the called
function. function.
In call by value, actual arguments will Incallbyreference, alteration to actual
remain safe, they cannot be modified argumentsispossiblewithinfromcalled
accidentally. functionthereforethecodemusthandle
arguments carefully else you get
unexpectedresults.
ExampleusingCallbyValue Adsby Google
The classic example of wanting to modify the caller's CCode
memory is a swapByValue() function which exchanges
C++Program
two values. For C uses call by value, the following
versionofswap swapByValue() willnotwork...
#include<stdio.h>
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 2/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
voidswapByValue(int,int);/*Prototype*/
intmain()/*Mainfunction*/
{
intn1=10,n2=20;
/*actualargumentswillbeasitis*/
swapByValue(n1,n2);
printf("n1:%d,n2:%d\n",n1,n2);
}
voidswapByValue(inta,intb)
{
intt;
t=a;a=b;b=t;
}
OUTPUT
======
n1:10,n2:20
The swapByValue() doesnotaffectthearguments n1 and n2 inthecallingfunctionit
onlyoperateson a and b localto swapByValue() itself.Thisisagoodexampleofhow
localvariablesbehave.
ExampleusingCallbyReference
Incallbyreference,topassavariable n asareferenceparameter,theprogrammer
mustpassapointerto n insteadof n itself.Theformalparameterwillbeapointerto
thevalueofinterest.Thecallingfunctionwillneedtouse & tocomputethepointer
ofactualparameter.Thecalledfunctionwillneedtodereferencethepointerwith *
where appropriate to access the value of interest. Here is an example of a correct
swap swapByReference() function. So, now you got the difference between call by
valueandcallbyreference!
#include<stdio.h>
voidswapByReference(int*,int*);/*Prototype*/
intmain()/*Mainfunction*/
{
intn1=10,n2=20;
/*actualargumentswillbealtered*/
swapByReference(&n1,&n2);
printf("n1:%d,n2:%d\n",n1,n2);
}
voidswapByReference(int*a,int*b)
{
intt;
t=*a;*a=*b;*b=t;
}
OUTPUT
======
n1:20,n2:10
Hope you have enjoyed reading differences between call by value and call by
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 3/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
referencemethodsofpassingparameterstofunctions Adsby Google
in C. Please do write us if you have any
CLanguage
suggestion/commentorcomeacrossanyerroronthis
page.Thanksforreading! CProgramSoftware
26Comments Sortby Oldest
Addacomment...
RituDadhwalNationalInstituteofTechnology,Hamirpur
thanksforaniceexample
LikeReply 6Oct5,201510:57am
KrishanKumarProjectLeadatOracle
welcomeRitu!
LikeReplyOct8,201510:12pm
RajsekharDhawaBeldaGangadharAcademy
It'sReallyNice.
LikeReplySep14,20167:52pm
AthikAhammadRoshanMyrelationshipdifferentatLoveFriendshipand
AttitudeswithGOD
itnice
LikeReply 2Nov7,201510:46pm
AdityaSingh12thatStudent
nicesir
.
LikeReply 1Dec8,20151:35pm
KumarVikashBCAatStudent(publication)
itisverytrue
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 4/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
itisverytrue
LikeReply 2Dec29,201510:59pm
KrishnaKumarEmbeddedSoftwareEngineeratTrinetra
gudexample..
LikeReply 1Jan3,20169:53pm
SnehasisDalal
yes,,,tyverymuch
LikeReply 1Feb8,201611:02pm
PrabhaKaranStudyingatStudying
thalada
LikeReply 1Feb25,201610:03pm
MajidGaddankeriWorksatStudent
cananyoneexplainhowtheactualargumentsalteredincallbyreference?
LikeReply 1Mar7,201611:25pm
AmanSinghNetajiSubhasInstituteofTechnology
Incallbyreferenceyouarepassingtheaddressoftheactualarguments.
sotheformalarguments(definedaspointers)aredirectlypointingtothe
samelocationwhereactualargumentsarestoredandanychangein
Calledfunctionwillaltertheactualarguments
LikeReplyMay22,201611:38am
ShashiKumarRevaInstituteofTechnologyandManagement
thanksalotithelpedalot.......
LikeReply 1Mar9,201612:39am
MuizzuddinAhmadTHEBURNatSMKSemenchu
voidmax_min(int&,int&)
incallbyrefrences,whatfunctionand(&)???
helpme
LikeReplyMar9,20167:14pm
Load10morecomments
FacebookCommentsPlugin
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 5/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
0Comments csfundamentals.com
1 Login
Recommend 3 Share SortbyOldest
Startthediscussion
Bethefirsttocomment.
ALSOONCSFUNDAMENTALS.COM
HowtoCompileandRunJava JavaPassbyValuePassby
PrograminLinux? Reference|JavaCallbyValueCall
2comments3yearsago 2comments3yearsago
aarchisharmathewayofexplanation JavaCoderSo,whatshouldwedoto
isverygood......"thankyou" actuallyswapthetwoobjectss1ands2?
ImplementsizeofOperatorinC CProgramtoFindEvenorOdd
2comments2yearsago UsingBitwiseOperator|C
Kannanintisizeofiandsizeof(i) 4comments3yearsago
bothworks...Canwehaveamacro csfundamentals.com intmain(void)
definedasthefirstone...? works.IexecuteditonLinuxbox.
Subscribe d AddDisqustoyoursiteAddDisqusAdd Privacy
GetFreeTutorialsbyEmail
Email:
Subscribe
19 1
13
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 6/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
AbouttheAuthor
Krishan Kumar is the
main author for cs
fundamentals.com. He is a
software professional (post
graduated from BITSPilani) and loves
writing technical articles on
programminganddatastructures.
Today'sTechNews
Mapstohelpdriversfindparking
spaces
PostedonMondaySeptember26,2016
Audi,BMWandMercedesBenzcars
fittedwithonboardsensorsaretoshare
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 7/8
9/26/2016 DifferenceBetweenCallbyValueandReferenceinC
informationinrealtimeaboutonstreet
parkingspacesandroadworksviaa
digitalmapservice.
Samsungdelaysrestartingsalesof
itsGalaxyNote7inSKorea
PostedonSundaySeptember25,2016
Samsungsaysitwilldelayrestartingthe
saleofitsGalaxyNote7phoneinSouth
Korea,toallowmoretimetorecallthe
deviceoverfaultybatteries.
UK'hasneverbeenmoreaddicted
tosmartphones'
PostedonMondaySeptember26,2016
Oneinthreepeoplechecktheirphonein
themiddleofthenightandadmittheir
overuseiscausingrowswithpartners,
accordingtoareportbyDeloitte.
CourtesyBBCNews
Home ContactUs AboutUs WriteForUs RSSFeed
copyright2016csFundamentals.com
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 8/8