0% found this document useful (0 votes)
35 views

Documentation of Data Function

The document discusses functions in C++. It explains that functions allow structuring programs into segments of code to perform individual tasks. It provides examples of defining and calling functions, and covers topics like function parameters, return values, and the void return type.

Uploaded by

Ben Clark
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Documentation of Data Function

The document discusses functions in C++. It explains that functions allow structuring programs into segments of code to perform individual tasks. It provides examples of defining and calling functions, and covers topics like function parameters, return values, and the void return type.

Uploaded by

Ben Clark
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

3/3/2015

FunctionsC++Tutorials
Search:
Tutorials

Go
C++Language

Notloggedin

Functions

register

login

C++
YouareusingaversionwithoutAdsofthiswebsite.Please,considerdonating:

Information
Tutorials
Reference
Articles
Forum

[hide]

Tutorials
C++Language
AsciiCodes
BooleanOperations
NumericalBases

C++Language
Introduction:
Compilers
BasicsofC++:
Structureofaprogram
Variablesandtypes
Constants
Operators
BasicInput/Output
Programstructure:
Statementsandflowcontrol
Functions
Overloadsandtemplates
Namevisibility
Compounddatatypes:
Arrays
Charactersequences
Pointers
Dynamicmemory
Datastructures
Otherdatatypes
Classes:
Classes(I)
Classes(II)
Specialmembers
Friendshipandinheritance
Polymorphism
Otherlanguagefeatures:
Typeconversions
Exceptions
Preprocessordirectives
Standardlibrary:
Input/outputwithfiles

1.ClickHeretoDownload
2.GetYourFreeSoftware3.Enjoy!

Functions
Functionsallowtostructureprogramsinsegmentsofcodetoperformindividualtasks.
InC++,afunctionisagroupofstatementsthatisgivenaname,andwhichcanbecalledfromsomepointofthe
program.Themostcommonsyntaxtodefineafunctionis:
typename(parameter1,parameter2,...){statements}
Where:
typeisthetypeofthevaluereturnedbythefunction.
nameistheidentifierbywhichthefunctioncanbecalled.
parameters(asmanyasneeded):Eachparameterconsistsofatypefollowedbyanidentifier,witheachparameterbeing
separatedfromthenextbyacomma.Eachparameterlooksverymuchlikearegularvariabledeclaration(forexample:
intx),andinfactactswithinthefunctionasaregularvariablewhichislocaltothefunction.Thepurposeofparameters
istoallowpassingargumentstothefunctionfromthelocationwhereitiscalledfrom.
statementsisthefunction'sbody.Itisablockofstatementssurroundedbybraces{}thatspecifywhatthefunction
actuallydoes.
Let'shavealookatanexample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

//functionexample
#include<iostream>
usingnamespacestd;

Theresultis8

intaddition(inta,intb)
{
intr;
r=a+b;
returnr;
}

Edit
&
Run

intmain()
{
intz;
z=addition(5,3);
cout<<"Theresultis"<<z;
}

Thisprogramisdividedintwofunctions:additionandmain.Rememberthatnomattertheorderinwhichtheyare
defined,aC++programalwaysstartsbycallingmain.Infact,mainistheonlyfunctioncalledautomatically,andthecode
inanyotherfunctionisonlyexecutedifitsfunctioniscalledfrommain(directlyorindirectly).
Intheexampleabove,mainbeginsbydeclaringthevariablezoftypeint,andrightafterthat,itperformsthefirst
functioncall:itcallsaddition.Thecalltoafunctionfollowsastructureverysimilartoitsdeclaration.Intheexample
above,thecalltoadditioncanbecomparedtoitsdefinitionjustafewlinesearlier:

Theparametersinthefunctiondeclarationhaveaclearcorrespondencetotheargumentspassedinthefunctioncall.The
callpassestwovalues,5and3,tothefunctionthesecorrespondtotheparametersaandb,declaredforfunction
addition.
Atthepointatwhichthefunctioniscalledfromwithinmain,thecontrolispassedtofunctionaddition:here,execution
ofmainisstopped,andwillonlyresumeoncetheadditionfunctionends.Atthemomentofthefunctioncall,thevalueof
botharguments(5and3)arecopiedtothelocalvariablesintaandintbwithinthefunction.
Then,insideaddition,anotherlocalvariableisdeclared(intr),andbymeansoftheexpressionr=a+b,theresultofa
plusbisassignedtorwhich,forthiscase,whereais5andbis3,meansthat8isassignedtor.
Thefinalstatementwithinthefunction:
returnr;

Endsfunctionaddition,andreturnsthecontrolbacktothepointwherethefunctionwascalledinthiscase:tofunction
main.Atthisprecisemoment,theprogramresumesitscourseonmainreturningexactlyatthesamepointatwhichit
wasinterruptedbythecalltoaddition.Butadditionally,becauseadditionhasareturntype,thecallisevaluatedas
havingavalue,andthisvalueisthevaluespecifiedinthereturnstatementthatendedaddition:inthisparticularcase,
thevalueofthelocalvariabler,whichatthemomentofthereturnstatementhadavalueof8.

Therefore,thecalltoadditionisanexpressionwiththevaluereturnedbythefunction,andinthiscase,thatvalue,8,is
assignedtoz.Itisasiftheentirefunctioncall(addition(5,3))wasreplacedbythevalueitreturns(i.e.,8).
Thenmainsimplyprintsthisvaluebycalling:
cout<<"Theresultis"<<z;

http://www.cplusplus.com/doc/tutorial/functions/

1/7

3/3/2015

FunctionsC++Tutorials

Afunctioncanactuallybecalledmultipletimeswithinaprogram,anditsargumentisnaturallynotlimitedjusttoliterals:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

//functionexample
#include<iostream>
usingnamespacestd;

Thefirstresultis5
Thesecondresultis5
Thethirdresultis2
Thefourthresultis6

intsubtraction(inta,intb)
{
intr;
r=ab;
returnr;
}

Edit
&
Run

intmain()
{
intx=5,y=3,z;
z=subtraction(7,2);
cout<<"Thefirstresultis"<<z<<'\n';
cout<<"Thesecondresultis"<<subtraction(7,2)<<'\n';
cout<<"Thethirdresultis"<<subtraction(x,y)<<'\n';
z=4+subtraction(x,y);
cout<<"Thefourthresultis"<<z<<'\n';
}

Similartotheadditionfunctioninthepreviousexample,thisexampledefinesasubtractfunction,thatsimplyreturns
thedifferencebetweenitstwoparameters.Thistime,maincallsthisfunctionseveraltimes,demonstratingmorepossible
waysinwhichafunctioncanbecalled.
Let'sexamineeachofthesecalls,bearinginmindthateachfunctioncallisitselfanexpressionthatisevaluatedasthe
valueitreturns.Again,youcanthinkofitasifthefunctioncallwasitselfreplacedbythereturnedvalue:
1 z=subtraction(7,2);
2 cout<<"Thefirstresultis"<<z;

Ifwereplacethefunctioncallbythevalueitreturns(i.e.,5),wewouldhave:
1 z=5;
2 cout<<"Thefirstresultis"<<z;

Withthesameprocedure,wecouldinterpret:
cout<<"Thesecondresultis"<<subtraction(7,2);

as:
cout<<"Thesecondresultis"<<5;

since5isthevaluereturnedbysubtraction(7,2).
Inthecaseof:
cout<<"Thethirdresultis"<<subtraction(x,y);

Theargumentspassedtosubtractionarevariablesinsteadofliterals.Thatisalsovalid,andworksfine.Thefunctionis
calledwiththevaluesxandyhaveatthemomentofthecall:5and3respectively,returning2asresult.
Thefourthcallisagainsimilar:
z=4+subtraction(x,y);

Theonlyadditionbeingthatnowthefunctioncallisalsoanoperandofanadditionoperation.Again,theresultisthe
sameasifthefunctioncallwasreplacedbyitsresult:6.Note,thatthankstothecommutativepropertyofadditions,the
abovecanalsobewrittenas:
z=subtraction(x,y)+4;

Withexactlythesameresult.Notealsothatthesemicolondoesnotnecessarilygoafterthefunctioncall,but,asalways,
attheendofthewholestatement.Again,thelogicbehindmaybeeasilyseenagainbyreplacingthefunctioncallsby
theirreturnedvalue:
1 z=4+2;//sameasz=4+subtraction(x,y);
2 z=2+4;//sameasz=subtraction(x,y)+4;

Functionswithnotype.Theuseofvoid
Thesyntaxshownaboveforfunctions:
typename(argument1,argument2...){statements}
Requiresthedeclarationtobeginwithatype.Thisisthetypeofthevaluereturnedbythefunction.Butwhatifthe
functiondoesnotneedtoreturnavalue?Inthiscase,thetypetobeusedisvoid,whichisaspecialtypetorepresent
theabsenceofvalue.Forexample,afunctionthatsimplyprintsamessagemaynotneedtoreturnanyvalue:
1 //voidfunctionexample
2 #include<iostream>

http://www.cplusplus.com/doc/tutorial/functions/

I'mafunction!

2/7

3/3/2015

FunctionsC++Tutorials
3
4
5
6
7
8
9
10
11
12
13

usingnamespacestd;
voidprintmessage()
{
cout<<"I'mafunction!";
}
intmain()
{
printmessage();
}

voidcanalsobeusedinthefunction'sparameterlisttoexplicitlyspecifythatthefunctiontakesnoactualparameters
whencalled.Forexample,printmessagecouldhavebeendeclaredas:
1
2
3
4

voidprintmessage(void)
{
cout<<"I'mafunction!";
}

InC++,anemptyparameterlistcanbeusedinsteadofvoidwithsamemeaning,buttheuseofvoidintheargument
listwaspopularizedbytheClanguage,wherethisisarequirement.
Somethingthatinnocaseisoptionalaretheparenthesesthatfollowthefunctionname,neitherinitsdeclarationnor
whencallingit.Andevenwhenthefunctiontakesnoparameters,atleastanemptypairofparenthesesshallalwaysbe
appendedtothefunctionname.Seehowprintmessagewascalledinanearlierexample:
printmessage();

Theparenthesesarewhatdifferentiatefunctionsfromotherkindsofdeclarationsorstatements.Thefollowingwouldnot
callthefunction:
printmessage;

Thereturnvalueofmain
Youmayhavenoticedthatthereturntypeofmainisint,butmostexamplesinthisandearlierchaptersdidnotactually
returnanyvaluefrommain.
Well,thereisacatch:Iftheexecutionofmainendsnormallywithoutencounteringareturnstatementthecompiler
assumesthefunctionendswithanimplicitreturnstatement:
return0;

Notethatthisonlyappliestofunctionmainforhistoricalreasons.Allotherfunctionswithareturntypeshallendwitha
properreturnstatementthatincludesareturnvalue,evenifthisisneverused.
Whenmainreturnszero(eitherimplicitlyorexplicitly),itisinterpretedbytheenvironmentasthattheprogramended
successfully.Othervaluesmaybereturnedbymain,andsomeenvironmentsgiveaccesstothatvaluetothecallerin
someway,althoughthisbehaviorisnotrequirednornecessarilyportablebetweenplatforms.Thevaluesformainthatare
guaranteedtobeinterpretedinthesamewayonallplatformsare:
value

description
Theprogramwassuccessful
Theprogramwassuccessful(sameasabove).
EXIT_SUCCESS
Thisvalueisdefinedinheader<cstdlib>.
Theprogramfailed.
EXIT_FAILURE
Thisvalueisdefinedinheader<cstdlib>.
0

Becausetheimplicitreturn0;statementformainisatrickyexception,someauthorsconsideritgoodpracticeto
explicitlywritethestatement.

Argumentspassedbyvalueandbyreference
Inthefunctionsseenearlier,argumentshavealwaysbeenpassedbyvalue.Thismeansthat,whencallingafunction,
whatispassedtothefunctionarethevaluesoftheseargumentsonthemomentofthecall,whicharecopiedintothe
variablesrepresentedbythefunctionparameters.Forexample,take:
1 intx=5,y=3,z;
2 z=addition(x,y);

Inthiscase,functionadditionispassed5and3,whicharecopiesofthevaluesofxandy,respectively.Thesevalues(5
and3)areusedtoinitializethevariablessetasparametersinthefunction'sdefinition,butanymodificationofthese
variableswithinthefunctionhasnoeffectonthevaluesofthevariablesxandyoutsideit,becausexandywere
themselvesnotpassedtothefunctiononthecall,butonlycopiesoftheirvaluesatthatmoment.

Incertaincases,though,itmaybeusefultoaccessanexternalvariablefromwithinafunction.Todothat,arguments
canbepassedbyreference,insteadofbyvalue.Forexample,thefunctionduplicateinthiscodeduplicatesthevalueof
itsthreearguments,causingthevariablesusedasargumentstoactuallybemodifiedbythecall:
1 //passingparametersbyreference
2 #include<iostream>
3 usingnamespacestd;

http://www.cplusplus.com/doc/tutorial/functions/

x=2,y=6,z=14
Edit
&

3/7

3/3/2015

FunctionsC++Tutorials
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

voidduplicate(int&a,int&b,int&c)
{
a*=2;
b*=2;
c*=2;
}
intmain()
{
intx=1,y=3,z=7;
duplicate(x,y,z);
cout<<"x="<<x<<",y="<<y<<",z="<<z;
return0;
}

Togainaccesstoitsarguments,thefunctiondeclaresitsparametersasreferences.InC++,referencesareindicatedwith
anampersand(&)followingtheparametertype,asintheparameterstakenbyduplicateintheexampleabove.
Whenavariableispassedbyreference,whatispassedisnolongeracopy,butthevariableitself,thevariableidentified
bythefunctionparameter,becomessomehowassociatedwiththeargumentpassedtothefunction,andany
modificationontheircorrespondinglocalvariableswithinthefunctionarereflectedinthevariablespassedasarguments
inthecall.

Infact,a,b,andcbecomealiasesoftheargumentspassedonthefunctioncall(x,y,andz)andanychangeonawithin
thefunctionisactuallymodifyingvariablexoutsidethefunction.Anychangeonbmodifiesy,andanychangeonc
modifiesz.Thatiswhywhen,intheexample,functionduplicatemodifiesthevaluesofvariablesa,b,andc,thevalues
ofx,y,andzareaffected.
Ifinsteadofdefiningduplicateas:
voidduplicate(int&a,int&b,int&c)

Wasittobedefinedwithouttheampersandsignsas:
voidduplicate(inta,intb,intc)

Thevariableswouldnotbepassedbyreference,butbyvalue,creatinginsteadcopiesoftheirvalues.Inthiscase,the
outputoftheprogramwouldhavebeenthevaluesofx,y,andzwithoutbeingmodified(i.e.,1,3,and7).

Efficiencyconsiderationsandconstreferences
Callingafunctionwithparameterstakenbyvaluecausescopiesofthevaluestobemade.Thisisarelativelyinexpensive
operationforfundamentaltypessuchasint,butiftheparameterisofalargecompoundtype,itmayresultoncertain
overhead.Forexample,considerthefollowingfunction:
1
2
3
4

stringconcatenate(stringa,stringb)
{
returna+b;
}

Thisfunctiontakestwostringsasparameters(byvalue),andreturnstheresultofconcatenatingthem.Bypassingthe
argumentsbyvalue,thefunctionforcesaandbtobecopiesoftheargumentspassedtothefunctionwhenitiscalled.
Andifthesearelongstrings,itmaymeancopyinglargequantitiesofdatajustforthefunctioncall.
Butthiscopycanbeavoidedaltogetherifbothparametersaremadereferences:
1
2
3
4

stringconcatenate(string&a,string&b)
{
returna+b;
}

Argumentsbyreferencedonotrequireacopy.Thefunctionoperatesdirectlyon(aliasesof)thestringspassedas
arguments,and,atmost,itmightmeanthetransferofcertainpointerstothefunction.Inthisregard,theversionof
concatenatetakingreferencesismoreefficientthantheversiontakingvalues,sinceitdoesnotneedtocopyexpensive
tocopystrings.
Ontheflipside,functionswithreferenceparametersaregenerallyperceivedasfunctionsthatmodifythearguments
passed,becausethatiswhyreferenceparametersareactuallyfor.
Thesolutionisforthefunctiontoguaranteethatitsreferenceparametersarenotgoingtobemodifiedbythisfunction.
Thiscanbedonebyqualifyingtheparametersasconstant:
1
2
3
4

stringconcatenate(conststring&a,conststring&b)
{
returna+b;
}

Byqualifyingthemasconst,thefunctionisforbiddentomodifythevaluesofneitheranorb,butcanactuallyaccess
theirvaluesasreferences(aliasesofthearguments),withouthavingtomakeactualcopiesofthestrings.
Therefore,constreferencesprovidefunctionalitysimilartopassingargumentsbyvalue,butwithanincreasedefficiency
forparametersoflargetypes.ThatiswhytheyareextremelypopularinC++forargumentsofcompoundtypes.Note
though,thatformostfundamentaltypes,thereisnonoticeabledifferenceinefficiency,andinsomecases,const

http://www.cplusplus.com/doc/tutorial/functions/

4/7

3/3/2015

FunctionsC++Tutorials
referencesmayevenbelessefficient!

Inlinefunctions
Callingafunctiongenerallycausesacertainoverhead(stackingarguments,jumps,etc...),andthusforveryshort
functions,itmaybemoreefficienttosimplyinsertthecodeofthefunctionwhereitiscalled,insteadofperformingthe
processofformallycallingafunction.
Precedingafunctiondeclarationwiththeinlinespecifierinformsthecompilerthatinlineexpansionispreferredoverthe
usualfunctioncallmechanismforaspecificfunction.Thisdoesnotchangeatallthebehaviorofafunction,butismerely
usedtosuggestthecompilerthatthecodegeneratedbythefunctionbodyshallbeinsertedateachpointthefunctionis
called,insteadofbeinginvokedwitharegularfunctioncall.
Forexample,theconcatenatefunctionabovemaybedeclaredinlineas:
1
2
3
4

inlinestringconcatenate(conststring&a,conststring&b)
{
returna+b;
}

Thisinformsthecompilerthatwhenconcatenateiscalled,theprogramprefersthefunctiontobeexpandedinline,
insteadofperformingaregularcall.inlineisonlyspecifiedinthefunctiondeclaration,notwhenitiscalled.
Notethatmostcompilersalreadyoptimizecodetogenerateinlinefunctionswhentheyseeanopportunitytoimprove
efficiency,evenifnotexplicitlymarkedwiththeinlinespecifier.Therefore,thisspecifiermerelyindicatesthecompiler
thatinlineispreferredforthisfunction,althoughthecompilerisfreetonotinlineit,andoptimizeotherwise.InC++,
optimizationisataskdelegatedtothecompiler,whichisfreetogenerateanycodeforaslongastheresultingbehavioris
theonespecifiedbythecode.

Defaultvaluesinparameters
InC++,functionscanalsohaveoptionalparameters,forwhichnoargumentsarerequiredinthecall,insuchawaythat,
forexample,afunctionwiththreeparametersmaybecalledwithonlytwo.Forthis,thefunctionshallincludeadefault
valueforitslastparameter,whichisusedbythefunctionwhencalledwithfewerarguments.Forexample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

//defaultvaluesinfunctions
#include<iostream>
usingnamespacestd;

6
5

intdivide(inta,intb=2)
{
intr;
r=a/b;
return(r);
}

Edit
&
Run

intmain()
{
cout<<divide(12)<<'\n';
cout<<divide(20,4)<<'\n';
return0;
}

Inthisexample,therearetwocallstofunctiondivide.Inthefirstone:
divide(12)

Thecallonlypassesoneargumenttothefunction,eventhoughthefunctionhastwoparameters.Inthiscase,the
functionassumesthesecondparametertobe2(noticethefunctiondefinition,whichdeclaresitssecondparameteras
intb=2).Therefore,theresultis6.
Inthesecondcall:
divide(20,4)

Thecallpassestwoargumentstothefunction.Therefore,thedefaultvalueforb(intb=2)isignored,andbtakesthe
valuepassedasargument,thatis4,yieldingaresultof5.

Declaringfunctions
InC++,identifierscanonlybeusedinexpressionsoncetheyhavebeendeclared.Forexample,somevariablexcannot
beusedbeforebeingdeclaredwithastatement,suchas:
intx;

Thesameappliestofunctions.Functionscannotbecalledbeforetheyaredeclared.Thatiswhy,inalltheprevious
examplesoffunctions,thefunctionswerealwaysdefinedbeforethemainfunction,whichisthefunctionfromwherethe
otherfunctionswerecalled.Ifmainweredefinedbeforetheotherfunctions,thiswouldbreaktherulethatfunctionsshall
bedeclaredbeforebeingused,andthuswouldnotcompile.
Theprototypeofafunctioncanbedeclaredwithoutactuallydefiningthefunctioncompletely,givingjustenoughdetails
toallowthetypesinvolvedinafunctioncalltobeknown.Naturally,thefunctionshallbedefinedsomewhereelse,like
laterinthecode.Butatleast,oncedeclaredlikethis,itcanalreadybecalled.
Thedeclarationshallincludealltypesinvolved(thereturntypeandthetypeofitsarguments),usingthesamesyntaxas
usedinthedefinitionofthefunction,butreplacingthebodyofthefunction(theblockofstatements)withanending
semicolon.
Theparameterlistdoesnotneedtoincludetheparameternames,butonlytheirtypes.Parameternamescan
neverthelessbespecified,buttheyareoptional,anddonotneedtonecessarilymatchthoseinthefunctiondefinition.For

http://www.cplusplus.com/doc/tutorial/functions/

5/7

3/3/2015

FunctionsC++Tutorials
example,afunctioncalledprotofunctionwithtwointparameterscanbedeclaredwitheitherofthesestatements:
1 intprotofunction(intfirst,intsecond);
2 intprotofunction(int,int);

Anyway,includinganameforeachparameteralwaysimproveslegibilityofthedeclaration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

//declaringfunctionsprototypes
#include<iostream>
usingnamespacestd;
voidodd(intx);
voideven(intx);
intmain()
{
inti;
do{
cout<<"Please,enternumber(0toexit):";
cin>>i;
odd(i);
}while(i!=0);
return0;
}

Please,enternumber(0toexit):9
Itisodd.
Please,enternumber(0toexit):6
Itiseven.
Please,enternumber(0toexit):1030
Itiseven.
Please,enternumber(0toexit):0
Itiseven.

Edit
&
Run

voidodd(intx)
{
if((x%2)!=0)cout<<"Itisodd.\n";
elseeven(x);
}
voideven(intx)
{
if((x%2)==0)cout<<"Itiseven.\n";
elseodd(x);
}

Thisexampleisindeednotanexampleofefficiency.Youcanprobablywriteyourselfaversionofthisprogramwithhalf
thelinesofcode.Anyway,thisexampleillustrateshowfunctionscanbedeclaredbeforeitsdefinition:
Thefollowinglines:
1 voidodd(inta);
2 voideven(inta);

Declaretheprototypeofthefunctions.Theyalreadycontainallwhatisnecessarytocallthem,theirname,thetypesof
theirargument,andtheirreturntype(voidinthiscase).Withtheseprototypedeclarationsinplace,theycanbecalled
beforetheyareentirelydefined,allowingforexample,toplacethefunctionfromwheretheyarecalled(main)beforethe
actualdefinitionofthesefunctions.
Butdeclaringfunctionsbeforebeingdefinedisnotonlyusefultoreorganizetheorderoffunctionswithinthecode.In
somecases,suchasinthisparticularcase,atleastoneofthedeclarationsisrequired,becauseoddandevenaremutually
calledthereisacalltoeveninoddandacalltooddineven.And,therefore,thereisnowaytostructurethecodesothat
oddisdefinedbeforeeven,andevenbeforeodd.

Recursivity
Recursivityisthepropertythatfunctionshavetobecalledbythemselves.Itisusefulforsometasks,suchassorting
elements,orcalculatingthefactorialofnumbers.Forexample,inordertoobtainthefactorialofanumber(n!)the
mathematicalformulawouldbe:
n!=n*(n1)*(n2)*(n3)...*1
Moreconcretely,5!(factorialof5)wouldbe:
5!=5*4*3*2*1=120
AndarecursivefunctiontocalculatethisinC++couldbe:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//factorialcalculator
#include<iostream>
usingnamespacestd;

9!=362880
Edit
&
Run

longfactorial(longa)
{
if(a>1)
return(a*factorial(a1));
else
return1;
}
intmain()
{
longnumber=9;
cout<<number<<"!="<<factorial(number);
return0;
}

Noticehowinfunctionfactorialweincludedacalltoitself,butonlyiftheargumentpassedwasgreaterthan1,since,
otherwise,thefunctionwouldperformaninfiniterecursiveloop,inwhichonceitarrivedto0,itwouldcontinue
multiplyingbyallthenegativenumbers(probablyprovokingastackoverflowatsomepointduringruntime).
Previous:
Statementsandflowcontrol

http://www.cplusplus.com/doc/tutorial/functions/

Index

Next:
Overloadsandtemplates

6/7

3/3/2015

FunctionsC++Tutorials

Homepage|Privacypolicy
cplusplus.com,20002015Allrightsreservedv3.1
Spottedanerror?contactus

http://www.cplusplus.com/doc/tutorial/functions/

7/7

You might also like