Difference Between Call by Value and Reference in C
Difference Between Call by Value and Reference in C
csFundamentals.com
ProgrammingTutorialsandInterviewQuestions
Home
CProgramming
JavaProgramming
DataStructures
WebDevelopment
TechInterview
Whatisthedifferencebetweencallbyvalueandcallby
referenceinClanguage?
DifferencebetweenCallby
ValueandCallbyReference
ExampleusingCallbyValue
ExampleusingCallby
Reference
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
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
#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
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
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
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.
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
copyright2016csFundamentals.com
http://csfundamentals.com/techinterview/c/differencebetweencallbyvalueandcallbyreferenceinc.php 8/8