Chiamata di funzione

Generalform

Intheprogram,thefunctionbodyisexecutedbycallingthefunction,andtheprocessissimilartothatofsubroutinecallsinotherlanguages.

InClanguage,thegeneralformoffunctioncallis:

Functionname(actualparameterlist)

Whencallingafunctionwithoutparameters,thereisnoactualparameterlist..Theparametersintheactualparametertablecanbeconstants,variables,orotherstructureddataandexpressions.Separateeachactualparameterwithacomma.

Userspace(usermode)andkernelspace(kernelmode)

Theprocessspaceoftheoperatingsystemcanbedividedintouserspaceandkernelspace,whichrequiredifferentexecutionpermissions.Thefunctioncallrunsinuserspace.

Includingcontent

Functionexpression

Functionsappearinexpressionsasoneitemofexpressions,andthereturnvalues​​offunctionsparticipateinthecalculationofexpressions.Thismethodrequiresthefunctiontohaveareturnvalue.Forexample:z=max(x,y)isanassignmentexpressionthatassignsthereturnvalueofmaxtothevariablez.

Functionstatement

Thegeneralformoffunctioncallplusasemicolonconstitutesafunctionstatement.Forexample:printf("%d",a);scanf("%d",&b);allcallfunctionsintheformoffunctionstatements.

FunctionArguments

Thefunctionappearsastheactualparameterofanotherfunctioncall.Inthiscase,thereturnvalueofthefunctionistransmittedasanactualparameter,sothefunctionmusthaveareturnvalue.Forexample:printf("%d",max(x,y));Thatis,thereturnvalueofthemaxcallisusedastheactualparameteroftheprintffunction.Anotherissuethatshouldbepaidattentiontoinfunctioncallsistheorderofevaluation.Theso-calledevaluationorderreferstowhetherthequantitiesintheactualparametertableareusedfromlefttorightorfromrighttoleft.Inthisregard,theregulationsofeachsystemarenotnecessarilythesame.Ithasbeenmentionedintheintroductionoftheprintffunction,andIwillemphasizeitagainfromtheperspectiveoffunctioncalls.

[Example]

main()

{inti=8;printf("%d\n%d\n%d\n%d\n",++i,--i,i++,i--);}

Ifitisevaluatedfromrighttoleft.Therunningresultshouldbe:

8

7

7

8

Forexample,intheprintfstatement++i,--i,i++,i--evaluatefromlefttoright,theresultshouldbe:

9

8

8

9

Itshouldbenotedthatwhetheritisevaluatedfromlefttorightorfromrighttoleft,theoutputorderisthesame,thatis,theoutputorderisalwaysTheorderoftheactualparametersisthesameasintheactualparameterlist.SinceTurboCiscurrentlyevaluatedfromrighttoleft,theresultis8,7,7,8.Ifyoustilldon’tunderstandtheabovequestions,youwillunderstandafteratryonthecomputer.

Declarationandfunctionprototypeofthecalledfunction

Beforecallingafunctioninthemaincallingfunction,thecalledfunctionshouldbeexplained(declared),whichisthesameasbeforeusingvariables.Thevariabledescriptionisthesame.Thepurposeofexplainingthecalledfunctioninthecallingfunctionistomakethecompilersystemknowthetypeofthereturnvalueofthecalledfunction,sothatthereturnvaluecanbeprocessedaccordinglyinthecallingfunctionaccordingtothistype.

Thegeneralformis:

Typespecifieriscalledfunctionname(typeparameter,typeparameter...);

Or:

Typespecifieriscalledfunctionname(type,type...);

Thetypeandnameoftheformalparameteraregivenintheparentheses,oronlythetypeoftheformalparameterisgiven.Thisfacilitateserrordetectionbythecompilersystemtopreventpossibleerrors.

Forexample,thedescriptionofthemaxfunctioninthemainfunctionis:

intmax(int​​a,intb);

Orwrittenas:

intmax(int,int);

TheClanguagealsostipulatesthatthefunctiondescriptionofthecalledfunctioninthecallingfunctioncanbeomittedinthefollowingsituations.

1)Ifthereturnvalueofthecalledfunctionisanintegerorcharactertype,youcancallthecalledfunctiondirectlywithoutexplainingit.Atthistime,thesystemwillautomaticallytreatthereturnvalueofthecalledfunctionasaninteger.ThisisthecasewhenthefunctionsisnotdescribedinthemainfunctionofExample8.2anditiscalleddirectly.

2)Whenthefunctiondefinitionofthecalledfunctionappearsbeforethecallingfunction,thecallingfunctioncanalsobecalleddirectlywithoutfurtherexplainingthecalledfunction.Forexample,inExample8.1,thedefinitionofthefunctionmaxisplacedbeforethemainfunction,sothefunctiondescriptionofthemaxfunctioncanbeomittedinthemainfunctionintmax(inta,intb).

3)Ifthetypeofeachfunctionisspecifiedoutsidethefunctionbeforethedefinitionofallthefunctions,theninthesubsequentcallingfunctions,thecalledfunctioncannolongerbedescribed.Forexample:

charstr(inta);

floatf(floatb);

main()

{……}

charstr(inta)

{……)

floatf(floatb)

{……}

Thefirstandsecondlineshavepre-explainedthestrfunctionandtheffunction.Therefore,thestrandffunctionscanbecalleddirectlyinthefollowingfunctionswithoutfurtherexplanation.

4)Thecallofthelibraryfunctiondoesnotneedtobeexplained,buttheheaderfileofthefunctionmustbeincludedinthefrontofthesourcefilewiththeincludecommand.

Nestedcall

NestedfunctiondefinitionsarenotallowedinClanguage.Therefore,thefunctionsareparallel,andthereisnoproblemoftheupperlevelfunctionandthenextlevelfunction.ButtheClanguageallowsacalltoanotherfunctiontoappearinthedefinitionofafunction.Inthisway,nestedcallsoffunctionsappear.Thatis,otherfunctionsarecalledinthecalledfunction.Thisissimilartothenestingofsubroutinesinotherlanguages.Therelationshipcanberepresentedasshowninthefigure.

Thefigureshowsatwo-levelnestingsituation.Theexecutionprocessis:whenthestatementthatcallsfunctionainthemainfunctionisexecuted,functionaisswitchedto,whenfunctionbiscalledinfunctiona,functionbisswitchedtoexecution,andfunctionbisexecutedtoreturntothebreakpointoffunctionatocontinueExecute,theexecutionoftheafunctioniscompleteandreturntothebreakpointofthemainfunctiontocontinueexecution.

[Example]Calculates=2∧2!+3∧2!

Thisquestioncanwritetwofunctions,oneisthefunctionf1usedtocalculatethesquarevalue,andtheotherisThefunctionf2usedtocalculatethefactorialvalue.Themainfunctionfirstadjustsf1tocalculatethesquarevalue,andthentakesthesquarevalueinf1astheactualparameter,callsf2tocalculatethefactorialvalue,andthenreturnstof1,thenreturnstothemainfunction,andcalculatesthecumulativesumintheloopprogram.

longf1(intp)

{intk;

longr;

longf2(int);

k=p*p;

r=f2(k);

returnr;}

longf2(intq)

p>

{longc=1;

inti;

for(i=1;i<=q;i++)

c=c*i;

returnc;}

main()

{inti;

longs=0;

p>

for(i=2;i<=3;i++)

s=s+f1(i);

printf("\ns=%ld\n",s);}

Intheprogram,thefunctionsf1andf2arebothlongintegers,whicharedefinedbeforethemainfunction,sothereisnoneedtoexplainf1andf2inthemainfunction.Inthemainprogram,theexecutionloopprogramsequentiallycallsthevalueofiastheactualparametertocallthefunctionf1toobtainthevalueofi2.Inf1,acalltofunctionf2occursagain.Atthistime,thevalueofi2isusedasanactualparametertoadjustf2,andthecalculationofi2!iscompletedinf2.Afterf2isexecuted,theCvalue(iei2!)isreturnedtof1,andthenf1returnstothemainfunctiontoachieveaccumulation.Sofar,therequirementoftheproblemisrealizedbythenestedcallofthefunction.Becausethevalueisverylarge,thetypesoffunctionsandsomevariablesaredeclaredaslongintegers,otherwiseitwillcausecalculationerrors.

Actualimplementation

Pointerregister

EBP

EBPistheso-calledframepointer,pointingtothecurrentactivityAbovetherecord(thebottomofthepreviousactivityrecord)

ESP

ESPistheso-calledstackpointer,whichpointstothebottomofthecurrentactivityrecord(bottomAnactivityrecordtobeinsertedatthetop)

Thevalueofthesetwopointersspecifiesthepositionofthecurrentactivityrecord

Parameterpassing

PressfunctionparametersStack:moveax,dwordptr[n];(nisaparameterargument)

pusheax

Operation

Thefunctioncallwillperformthefollowingoperations:

⒈Pushtheframepointerontothestack:pushebp

⒉maketheframepointerequaltothestackpointer:movebp,esp

⒊makethestackpointerdecrement,Thememoryaddressobtainedbysubtractionshouldbeableto(enough)beusedtostorethelocalstateofthecalledfunction:subesp,0CCh

Note:0CChis0xCC,whichvarieswiththespecificfunction.

Passinsavestate

pushebx;savethevalueofebxregister

pushesi;savethevalueofesiregister

pushedi;Savethevalueoftheediregister

Loadedi

leaedi,[ebp-0CCh];0cchisthesizeofthecurrentactiverecord.

EDIisthedestinationindexregister.

Restoretheincomingsavestate

00411417popedi

00411418popesi

popebx

stackMovethepointeruptorestorespace

addesp,0CCh

Functionreturnstoreleasespace

Whenthefunctionreturns,thecompilerandhardwarewillperformthefollowingoperations:

⒈Makethestackpointerequaltotheframepointer:movesp,ebp

⒉Poptheoldframepointerfromthestack:popebp

⒊Return:ret

Example1

;voidfunction(intn);{pushebp

movebp,esp

subesp,0CCh

pushebx

pushesi

pushedi

leaedi,[ebp-0CCh]

movecx,33h

moveax,0CCCCCCCCh

repstosdwordptres:[edi]

;chara=1;

movbyteptr[a],1

;if(n==0)return;

cmpdwordptr[n],0

jnefunction+2Ah(4113CAh)

jmpfunction+77h(411417h)

;printf("%d\t(0x%08x)\n",n,&n);

movesi,esp

leaeax,[n]

pusheax

movecx,dwordptr[n]

pushecx

pushoffsetstring"%d\t(0x%08x)\n"(415750h)

calldwordptr[__imp__printf(4182B8h)]

addesp,0Ch

cmpesi,esp

call@ILT+305(__RTC_CheckEsp)(411136h)

;function(n-1);

moveax,dwordptr[n]

subeax,1

pusheax

callfunction(411041h)

addesp,4

;printf("----%d\t(0x%08x)\n",n,&n);

movesi,esp

leaeax,[n]

pusheax

movecx,dwordptr[n]

pushecx

pushoffsetstring"----%d\t(0x%08x)\n"(41573Ch)

calldwordptr[__imp__printf(4182B8h)]

addesp,0Ch

cmpesi,esp

call@ILT+305(__RTC_CheckEsp)(411136h);}

popedi

popesi

popebx

addesp,0CCh

cmpebp,esp

call@ILT+305(__RTC_CheckEsp)(411136h)

movesp,ebp

popebp

ret

Example2

117:bR=t1(p);

Theassemblycodeisasfollows:

00401FB8movecx,dwordptr[ebp-8];puttheparameterintotheecxregister

00401FBBpushecx;theparameterintothestack

00401FBCcall@ILT+10(t1)(0040100f);Functioncall,thenextlineaddress00401FC1ispushedintothestack

00401FC1addesp,4;Thefunctionreturns,thestackpointerisincreasedby4,anditisrestoredtothevalueat00401FB8

00401FC4movdwordptr[ebp-10h],eax;Takethefunctionreturnvalueinthehigh-levellanguagefromeaxandputitintothebRvariable

Thet1functionisasfollows:

125:BOOLt1(void*p)

126:{

00402030pushebp;ebpintothestack

00402031movebp,esp;ebppointstothetopofthestackatthistime

00402033subesp,44h;espdecreasesbyonevalueandfreesupastoragearea

p>

00402036pushebx;Putthevalues​​ofthethreeregistersontothestacksothatyoucanuseitinthefunction

00402037pushesi;

00402038pushedi;

00402039leaedi,[ebp-44h];

0040203Cmovecx,11h;

00402041moveax,0CCCCCCCCh;

00402046repstosdwordptr[edi];

127:int*q=(int*)p;;

00402048moveax,dwordptr[ebp+8];ebp+8pointstofunctioninputThelowestbitaddressoftheparameter;

;ifitisebp+4,itpointstothelowestbitofthefunctionreturnaddress00401FC1,thevalueisC1

0040204Bmovdwordptr[ebp-4],eax;

128:return0;

0040204Exoreax,eax;Thereturnvalueisplacedintheeaxregister

129:}

00402050popedi;Threeregisterspopoutofthestack

00402051popesi;

00402052popebx;

00402053movesp,ebp;esprestore

00402055popebp;ebppopsoutofthestack,anditsvalueisrestored

00402056ret;Returntothecodeaddressstoredatthetopofthestackatthistime:00401FC1

;soifyouareunluckyIfthereturnaddressismodified,theprogramwillbeunexpected

TheaboveassemblycodeiscompiledbyVC++6.0.

ThesituationofthestackaftertheEBPisputintothestack:

Lowandhigh

↓↓

Memoryaddressstack

┆┆

0012F600├───────┤←edi=0012F600

││

0012F604├─┄┄┄┄─┤

││

││

┆44hspace┆

┆┆

││

││

0012F640├─┄┄┄┄─┤

││

0012F644├───────┤←Ebpisassignedtopointtothisunit,atthistimeebp=0012F644

│ACF61200│ebpisassignedtothevaluebeforeesp

0012F648├────────┤

│C11F4000│Returnaddress

0012F64C├─────────┤←ebp+8

│A0F61200│Thevalueofthefunctionparameterp;

0012F650├─────────┤

││

├────────┤

┆┆

Note:Thememorystoragespacestackisarrangedfromhightolow,andtheaddressmarkedontheleftisthelowestaddressofthestorageunitatthebottomright.Forexample,0012F644pointstotheACbyteof0012F6AC,andACisatthetopofthestack.Thecontentinthememoryinthefigureiswrittenfromlowtohigh,"ACF61200"=0x0012F6AC

Explanation

(1)Acprogramiscomposedofoneormoreprogrammodules,Eachprogrammoduleasasourceprogramfile.Forlargerprograms,yougenerallydon'twanttoputallthecontentinonefile,butputtheminseveralsourcefiles,andacprogramiscomposedofseveralsourceprogramfiles.Thismakesiteasytowriteandcompileseparately,andimprovedebuggingefficiency.Asourceprogramfilecanbesharedbymultiplecprograms.

(2)Asourceprogramfileiscomposedofoneormorefunctionsandotherrelatedcontent(suchasinstructions,datadeclarationsanddefinitions,etc.).Asourceprogramfileisacompilationunit,andthesubprogramiscompiledintheunitofthesourceprogramfile,notintheunitofthefunction.

(3)Theexecutionofthecprogramstartsfromthemainfunction.Ifyoucallotherfunctionsinthemainfunction,theprocessreturnstothemainfunctionafterthecall,andthewholeprogramendsinthemainfunction.

(4)Allfunctionsareparallel,thatis,whendefiningfunctions,theyareperformedseparatelyandareindependentofeachother.Afunctionisnotsubordinatetoanotherfunction,thatis,functionscannotbenesteddefinitions.Functionscancalleachother,butcannotcallthemainfunction.Themainfunctioniscalledbytheoperatingsystem.

(5)Fromtheuser'spointofview,therearetwotypesoffunctions

a:libraryfunctions,whichareprovidedbythesystem,andusersdonotneedtodefinethembythemselves,butcanusethemdirectly.Itshouldbenotedthatthenumberandfunctionsoflibraryfunctionsprovidedbydifferentclanguagecompilationsystemswillbesomewhatdifferent,ofcourse,manybasicfunctionsarecommon.

b:User-definedfunction.Itisafunctionthataddressesthespecificneedsofusers.

(6)Fromtheformoffunctions,functionsaredividedintotwocategories.

a:Functionwithoutparameters.No-parameterfunctionscanbringbackordonotbringbackfunctionvalues,butgenerallytherearemorefunctionvalues​​thatdonotbringback.

b:Functionwithparameters.Whencallingafunction,thecallingfunctionpassesdatatothecalledfunctionthroughparameterswhencallingthecalledfunction.Undernormalcircumstances,afunctionvaluewillbeobtainedwhenthecallingfunctionisexecuted,whichcanbeusedbythecallingfunction.

Related Articles
TOP