Вы находитесь на странице: 1из 3

5/15/2017 CFunctions

CFunctions
Advertisements

PreviousPage NextPage

Afunctionisagroupofstatementsthattogetherperformatask.EveryCprogramhasatleastonefunction,whichismain(),andallthe
mosttrivialprogramscandefineadditionalfunctions.

Youcandivideupyourcodeintoseparatefunctions.Howyoudivideupyourcodeamongdifferentfunctionsisuptoyou,butlogicallythe
divisionissuchthateachfunctionperformsaspecifictask.

Afunctiondeclarationtellsthecompileraboutafunction'sname,returntype,andparameters.Afunctiondefinitionprovidestheactual
bodyofthefunction.

TheCstandardlibraryprovidesnumerousbuiltinfunctionsthatyourprogramcancall.Forexample,strcat()toconcatenatetwostrings,
memcpy()tocopyonememorylocationtoanotherlocation,andmanymorefunctions.

Afunctioncanalsobereferredasamethodorasubroutineoraprocedure,etc.

DefiningaFunction
ThegeneralformofafunctiondefinitioninCprogramminglanguageisasfollows

return_typefunction_name(parameterlist){
bodyofthefunction
}

AfunctiondefinitioninCprogrammingconsistsofafunctionheaderandafunctionbody.Hereareallthepartsofafunction

ReturnTypeAfunctionmayreturnavalue.Thereturn_typeisthedatatypeofthevaluethefunctionreturns.Somefunctions
performthedesiredoperationswithoutreturningavalue.Inthiscase,thereturn_typeisthekeywordvoid.

FunctionNameThisistheactualnameofthefunction.Thefunctionnameandtheparameterlisttogetherconstitutethefunction
signature.

ParametersAparameterislikeaplaceholder.Whenafunctionisinvoked,youpassavaluetotheparameter.Thisvalueisreferred
to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function.
Parametersareoptionalthatis,afunctionmaycontainnoparameters.

FunctionBodyThefunctionbodycontainsacollectionofstatementsthatdefinewhatthefunctiondoes.

Example
Givenbelowisthesourcecodeforafunctioncalledmax().Thisfunctiontakestwoparametersnum1andnum2andreturnsthemaximum
valuebetweenthetwo

/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){

/*localvariabledeclaration*/
intresult;

if(num1>num2)
result=num1;
else
result=num2;

returnresult;
}

FunctionDeclarations
Afunctiondeclarationtellsthecompileraboutafunctionnameandhowtocallthefunction.Theactualbodyofthefunctioncanbedefined
separately.

https://www.tutorialspoint.com/cprogramming/c_functions.htm 1/3
5/15/2017 CFunctions

Afunctiondeclarationhasthefollowingparts

return_typefunction_name(parameterlist);

Fortheabovedefinedfunctionmax(),thefunctiondeclarationisasfollows

intmax(intnum1,intnum2);

Parameternamesarenotimportantinfunctiondeclarationonlytheirtypeisrequired,sothefollowingisalsoavaliddeclaration

intmax(int,int);

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you
shoulddeclarethefunctionatthetopofthefilecallingthefunction.

CallingaFunction
While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to
performthedefinedtask.

Whenaprogramcallsafunction,theprogramcontrolistransferredtothecalledfunction.Acalledfunctionperformsadefinedtaskandwhen
its return statement is executed or when its functionending closing brace is reached, it returns the program control back to the main
program.

Tocallafunction,yousimplyneedtopasstherequiredparametersalongwiththefunctionname,andifthefunctionreturnsavalue,thenyou
canstorethereturnedvalue.Forexample

#include<stdio.h>

/*functiondeclaration*/
intmax(intnum1,intnum2);

intmain(){

/*localvariabledefinition*/
inta=100;
intb=200;
intret;

/*callingafunctiontogetmaxvalue*/
ret=max(a,b);

printf("Maxvalueis:%d\n",ret);

return0;
}

/*functionreturningthemaxbetweentwonumbers*/
intmax(intnum1,intnum2){

/*localvariabledeclaration*/
intresult;

if(num1>num2)
result=num1;
else
result=num2;

returnresult;
}

Wehavekeptmax()alongwithmain()andcompiledthesourcecode.Whilerunningthefinalexecutable,itwouldproducethefollowingresult

Maxvalueis:200

FunctionArguments
Ifafunctionistousearguments,itmustdeclarevariablesthatacceptthevaluesofthearguments.Thesevariablesarecalledtheformal
parametersofthefunction.

Formalparametersbehavelikeotherlocalvariablesinsidethefunctionandarecreateduponentryintothefunctionanddestroyeduponexit.

Whilecallingafunction,therearetwowaysinwhichargumentscanbepassedtoafunction

S.N. CallType&Description

1 Callbyvalue

https://www.tutorialspoint.com/cprogramming/c_functions.htm 2/3
5/15/2017 CFunctions

Thismethodcopiestheactualvalueofanargumentintotheformalparameterofthefunction.Inthiscase,changesmadetothe
parameterinsidethefunctionhavenoeffectontheargument.

2 Callbyreference
Thismethodcopiestheaddressofanargumentintotheformalparameter.Insidethefunction,theaddressisusedtoaccessthe
actualargumentusedinthecall.Thismeansthatchangesmadetotheparameteraffecttheargument.

Bydefault,Cusescallbyvaluetopassarguments.Ingeneral,itmeansthecodewithinafunctioncannotaltertheargumentsusedtocall
thefunction.

PreviousPage NextPage

Advertisements

Write for us FAQ's Helping Contact


Copyright 2017. All Rights Reserved.

Enter email for newsletter go

https://www.tutorialspoint.com/cprogramming/c_functions.htm 3/3

Вам также может понравиться