1、LOGOFunction and Program Structure Chapter Four ContentsBasicsofFunctionsBasicsofFunctions 1returnstatementsreturnstatements2LocalvariablesandLocalvariablesandexternavariablesexternavariables3RecursionRecursion4ScopeRules 5HeaderFilesHeaderFiles6StaticVariablesStaticVariables7RegisterVariablesRegist
2、erVariables89TheCPreprocessorTheCPreprocessorFunction and Program Structure 老师让几个同学编程,老师让几个同学编程,A负责编写求两个数的最大公约数;负责编写求两个数的最大公约数;B负责两个负责两个数的最小公倍数;数的最小公倍数;C负责判断这两个数是不是亲密数;负责判断这两个数是不是亲密数;D负责计算这两负责计算这两个数中有多少既能被个数中有多少既能被3整除又能被整除又能被7整除的数整除的数老师说出了两个数,老师说出了两个数,A,B,C,D立即把自己程序运行的结果告诉老师;立即把自己程序运行的结果告诉老师;老师又说了另外
3、两个数,老师又说了另外两个数,A,B,C,D又给出新的结果又给出新的结果A AB BC CD Dmain()(int a,b;scanf(“%d,%d”,&a,&b);funa(a,b);funb(a,b);func(a,b);fund(a,b);36,120main()(int a,b;scanf(“%d,%d”,&a,&b);funa(a,b);funb(a,b);func(a,b);fund(a,b);36,120Function and Program Structure A Ammain()ain()intint a,b,ha,b,h;s scanf(“%d,%d”,&a,&bcan
4、f(“%d,%d”,&a,&b););if(aif(ab)b)a=a=a+ba+b;b=a-b;b=a-b;a=a-b;a=a-b;f for(hor(h=a;ha;h=2;h-)=2;h-)I If(f(a%ha%h=0&b%h=0)=0&b%h=0)b break;reak;p printf(“%d,%d,%d”,a,b,hrintf(“%d,%d,%d”,a,b,h););funafuna(intint a,a,intint b)b)intint h;h;if(aif(ab)b)a=a=a+ba+b;b=a-b;b=a-b;a=a-b;a=a-b;f for(hor(h=a;ha;h=2
5、;h-)=2;h-)I If(f(a%ha%h=0&b%h=0)=0&b%h=0)b break;reak;p printf(“%d,%d,%d”,a,b,hrintf(“%d,%d,%d”,a,b,h););return;return;main()(int a,b;scanf(“%d,%d”,&a,&b);funa(a,b);funb(a,b);func(a,b);fund(a,b);36,120Function and Program Structure C program source1source2source3.sourcenTheCPreprocessorTheCPreproces
6、sorfunction1function1function2function2.functiofunctionnnnFunction is the smallest unit in C program.Function definitions can appear in any order,and in one source file or severalAprogrammayresideinoneormoresourcefilesmoresourcefiles.Sourcefilesmaybecompiledseparatelycompiledseparatelyandloadedtoget
7、her,alongwithpreviouslycompiledfunctionsfromlibrariesFunctionDeclarationStatementExecutiveStatementVariablesFunctionprototypeVariablestypeVariablenameBlankstatementFunctioncallstatementControlstatementBlockstructureExpressionstatementFunction and Program Structure Aprogramisjustasetofdefinitionsofva
8、riablesandfunctions.Communicationbetweenthefunctionsisbyargumentsandvaluesreturnedbythefunctions,andthroughexternalvariables.DefinitionDefinitionPrototypePrototypeCallCallReturn Return ArgumentsArgumentsBasics of Functions1 The types of functions Type Standard Standard functionsfunctions(librarylibr
9、ary)Need use head files#include User-defined User-defined functionsfunctionsEach function definition has the form 2 Definition of a function return-typefunction-name(argumentdeclarations)declarationsstatements The type of the result that the function returns parameter types and names If return type
10、is omitted,int is assumed A minimal function is empty function,which does nothing and returns nothing.Basics of Functionsfunc()printf(“*n”);main()inti;main()for(i=1;i4;i+)func();printf(“*n”);func();func();main()inti;for(i=1;iy?x:y;return(n);BasicsofFunctionsinput:6.8,4.5 m=?thereisnofunctiondeclarat
11、ionincaller.returntypeisfloat,theactualtypeofreturnvalueisint.floatm;%freturnstatement1returnstatementreturn expression;Thereturnstatementisthemechanismforreturningavaluefromthecalledfunctiontoitscaller.Afunctionneedntreturnavalue,theexpressioncanbeomitted,ornoreturnstatement.Areturnstatementwithnoe
12、xpressionpassesanousefulvaluetothecaller.Sometimesitisatrouble.whendefiningfunctiontypeto“void”,noanyvaluereturned.Itisallowedthatseveralreturnstatementsoccurinafunction.voidfunctionname()floatf(floatx,floaty)floatz;z=x+y*y;if(!y)return(0.0);return(cos(z);1.return(ab?a:b);2.return(0);3.return(x);4.r
13、etrun;5.noreturnstatement6.voidreturn statementmain()inta;voiddisp();printf(“Enteraninteger:n”);scanf(“%d”,&a);disp(a);Ifyiszero,return0Otherwisereturncos(z)voiddisp(intx)if(x0)printf(“Positive.n”);elseif(x=0)printf(“Zero.n”);elseprintf(“Negative.n”);5nesting-function.returnstatementwhilecallingafun
14、ction,anotherfunctioniscalled.fun1().fun2().fun3().fun1().fun2().nesting-functiondoesnotmeannesting-definition.voidbeijing();voidshanghai();voidtianjin();main()printf(“Iminmain.n”);beijing();printf(“Imfinallybackinmain().n”);voidbeijing()printf(“Iminbeijing.n”);shanghai();printf(“HereImbackinbeijing
15、.n”);voidshanghai()printf(“NowIminshanghai.n”);tianjin();printf(“NowImbackinshanghai.n”);voidtianjin()printf(“Imintianjinnow.n”);m m m main()ain()ain()ain()callcallfuncfunc A;A;A;A;funcfunc A Ac callallfuncfunc B B;funcfuncBB return statementLocalvariablesandexternalvariablesexternalLocalinnerFuncti
16、onBlockOut of int x,y;main()int a,b,c;.fun(a,b);.int fun(int m).shareLocalvariablesandexternalvariables 1.localvariablesDeclaredwithinafunctionorablock.Canonlybeusedinthefunctionortheblockwhichdefinethem.Theyarecreatedaneweachtimethefunctioniscalled,anddestroyedonreturnfromthefunctionoroutsidetheblo
17、ck.Theyarenotvisibleforotherfunctions.LocalvariablesindifferentfunctionscansharethesamenameTheformalargumentsaretreatedlikelocalvariablesfloat f(int a)int b,c;a,b,c are local variablesmain()intx=10;intx=20;printf(“%d“,x);printf(“%d“,x);Localvariablesandexternalvariablesmain()intx=1;voidf1(),f2();f1(
18、);f2(x);printf(“%cn”,x);voidf1()intx=3;printf(“%d”,x);voidf2(intx)printf(“%d”,+x);2.ExternalvariablesDefinedoutsideanyfunctionTheirvalueisretainedandisavailabletoanyotherfunctionwhichaccessesthem.CanbeinitializedonlyonceCansharethesamenamewithlocalvariable,butthelatterisusefulwithinthenamingfunction
19、.shouldbedeclaredifuseitbeforeitsdefinition.Localvariablesandexternalvariables extern int a;main()int I;for(I=1;I=10)then output the lowest digit;N is divided 10 N-N-1;call function itself(N-N-1 );else output N;main()intx;printf(“nEnterN=”);scanf(“%d”,&x);int_turn(x);int_turn(n)intn;if(n=10)printf(“
20、%d”,n%10);int_turn(n/10);elseprintf(“%d”,n);Recursionvoid move(char getone,char putone)printf(%c-%cn,getone,putone);void hanoi(int n,char one,char two,char three)if(n=1)move(one,three);else hanoi(n-1,one,three,two);move(one,three);hanoi(n-1,two,one,three);main()int m;printf(Input the number of disks
21、:);scanf(%d,&m);printf(The steps to moving%3d disks:n,m);hanoi(m,A,B,C);HanoiproblemRecursionABCHanoiproblem Scope Rules How are declarations written so that variables are properly declared during compilation?How are declarations arranged so that all the pieces will be properly connected when the pr
22、ogram is loaded?How are declarations organized so there is only one copy?How are external variables initialized?Scope Rules external variableDeclare in a function or blockCan only be used in the function or blockDeclare at any place out of functionlasts from the point at which it is declared to the
23、end of the file being compiledLocalvariablesofthesamenameindifferentfunctionsareunrelatedIfanexternalvariableistobereferedtobeforeitisdefined,orifitisdefinedinadifferentsourcefilefromtheonewhereitisbeingused,thenanexterndeclarationismandatory.Local variableTheremustbeonlyonedefinitionofanexternalvar
24、iableamongallthefilesthatmakeupthesourceprogram;otherfilesmaycontainexterndeclarationstoaccessit.Scope Rules externalvariablesautovariablesregistervariablesstaticvariablesKey wordsexternautoregisterstaticThe memory can be devided several parts:programStatic storageDynamic storagememoryCPUregisterSto
25、reprogramStorestaticvariablesStoredynamicvariablesAccordingtothewayofstorage,wehave:Scope Rules Key wordsexternautoregisterstaticThedefaulttypeisauto Scope Rules Thekey-word:staticTwokinds:staticexternalvariablestaticinternalvariableTheirvaluealwaysexistinmemory.main()inti;for(i=1;i=5;i+)f(i);f(intj
26、)staticinta=100;autok=1;+k;printf(“%d+%d+%d=%dn”,a,k,j,a+k+j);a+=10;1.Staticinternalvariableinternalstaticvariablesprovideprivate,permanentstoragewithinasinglefunction.Scope Rules DeclaredwithinafunctionCanonlybeusedinthefunctionwhichdefinethem.Theyarenotvisibleforotherfunctions.Staticvariablesindif
27、ferentfunctionscansharethesamenameTheyremaininexistenceratherthancomingandgoingeachtimethefunctionisactivated.staticinternalvariable intf(inta)autointb=0;staticintc=3;b+;c+;returna+b+c;main()intc,a=1;for(c=1;c3;c+)printf(“%dn”,f(a);Scope Rules Scope Rules staticexternalvariable 2.Staticexternalvaria
28、bleDeclaredoutsideanyfunctionLimitsthescopeofthatobjecttotherestofthesourcefilebeingcompiled.Externalstaticthusprovidesawaytohidenames,whichmustbeexternalsotheycanbeshared,yetwhichshouldnotbevisibletoothersfiles.Canonlybeusedinthefilewhichdefineit Scope Rules registervariablesregistervariablesregist
29、erregister Aregisterdeclarationadvisesthecompilerthatthevariableinquestionwillbeheavilyusedheavilyused.Thatregistervariablesaretobeplacedinmachineregistersplacedinmachineregisters.TheregisterdeclarationcanonlybeappliedtoautomaticvariablesandtotheformalparametersofafunctionOnlyafewvariablesineachfunc
30、tionmaybekeptinregisters,Onlycertaintypes(int,char)areallowed.Scope Rules BlockStructure Variables can be defined in a block-structured fashion within a functionintk=1;.fun(intm)m+=k;k+=m;chark=B;printf(“n%d”,k-A);printf(“%d,%d”,m,k);12Declarations of variables(including initializations)may follow t
31、he left brace that introduces anycompoundstatement.Variables declared in this way hide any identically named variables in outer blocks,and remain in existence until the matching right braceInitialization Scope Rules Intheabsenceofexplicitinitialization,externalandstaticvariablesareguaranteedtobeinit
32、ializedtozero.Automaticandregistervariableshaveundefined(i.e.,garbage)initialvalues.Forexternalandstaticvariables,theinitializermustbeaconstantexpression;theinitializationisdoneonce.Forautomaticandregistervariables,theinitializerisnotrestrictedtobeingaconstantmain()int x=1;void prt(void);int x=3;prt
33、();printf(“2nd x=%dn”,x);printf(“1st x=%dn”,x);void prt(void)int x=5;printf(“3th x=%dn”,x);result:3th x=52nd x=31st x=1x=1 scopex=1 scopex=3 scopex=5 scope Scope Rules main()voidincrement(void);increment();increment();increment();voidincrement(void)intx=0;x+;printf(“%dn”,x);result:1 1 1main()voidincrement(void);increment();increment();increment();voidincrement(void)staticintx=0;x+;printf(“%dn”,x);