![C程序设计基础 英文版 课件 Chapter 6 Functions、Chapter 7 Pointers_第1页](http://file4.renrendoc.com/view11/M03/18/3D/wKhkGWWyjuaAHcE4AABSP6IyFsc135.jpg)
![C程序设计基础 英文版 课件 Chapter 6 Functions、Chapter 7 Pointers_第2页](http://file4.renrendoc.com/view11/M03/18/3D/wKhkGWWyjuaAHcE4AABSP6IyFsc1352.jpg)
![C程序设计基础 英文版 课件 Chapter 6 Functions、Chapter 7 Pointers_第3页](http://file4.renrendoc.com/view11/M03/18/3D/wKhkGWWyjuaAHcE4AABSP6IyFsc1353.jpg)
![C程序设计基础 英文版 课件 Chapter 6 Functions、Chapter 7 Pointers_第4页](http://file4.renrendoc.com/view11/M03/18/3D/wKhkGWWyjuaAHcE4AABSP6IyFsc1354.jpg)
![C程序设计基础 英文版 课件 Chapter 6 Functions、Chapter 7 Pointers_第5页](http://file4.renrendoc.com/view11/M03/18/3D/wKhkGWWyjuaAHcE4AABSP6IyFsc1355.jpg)
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter6Functions函数Outlines6.1Introduction6.2DefiningandCallingFunctions6.3Arguments6.4ThereturnStatement6.5Declarations6.6ArrayArguments6.7Recursion6.8SortAlgorithm6.9ProgramOrganization26.1IntroductionAfunctionisaseriesofstatementsthathavebeengroupedtogetherandgivenaname.
Advantagesoffunctions:easiertounderstandandmodify.avoidduplicatingcodecanbereusedinotherprograms.6.1IntroductionTypesoffunctionStandardlibraryfunctions:printf()scanf()sqrt()
User-definedfunctionscharacteristics:5Basicallyafunctionhasthefollowingcharacteristics:Namedwithauniquename.Performsaspecifictask.May(ormaynot)receivevaluesfromthecallingfunction(caller)-Callingfunctioncanpassvaluestofunctionforprocessing.May(ormaynot)returnavaluetothecallingfunction–thecalledfunctionmaypasssomethingbacktothecallingfunction.FunctionMechanism6Cprogramdoesnotexecutethestatementsinafunctionuntilthefunctioniscalled.Whenthefunctionfinishedprocessing,programreturnstothesamelocationwhichcalledthefunction.Whenitiscalled,theprogramcansendinformationtothefunctionintheformofoneormorearguments.Argumentisaprogramdataneededbythefunctiontoperformitstask.①Simplestformofafunctiondefinition
(noreturnnoparameter)7intmain(){statements;return0;}voidfunction_name() {
statements; }FunctionheaderFunctionbody#include<stdio.h>voidfunctionName
(){ ……….. ………..}intmain()//Start{………..functionName();………..}//EndCallingafunction6.2DefiningandCallingFunctions6.2DefiningandCallingFunctions#include<stdio.h>voidprintsomething(){printf("Hi,Iamafunction!\n");}intmain(){
printsomething();
return0;}Callfunction//Noreturnvalue,noparametersNoreturn,noarguments没有参数,没有返回值的函数#include<stdio.h>#include<stdlib.h>voidprintsomething();intmain(){
printsomething();return0;}voidprintsomething(){printf("Hi,Iamafunction!\n");}
//ThisisaUser-definedfunctionCProgrammingTutorial-54–Functions(5:57-6:06)10functon-printsth.c用户自定义的函数只能通过函数调用的方式执行。没有被调用,它就不会被执行//functionmainbeginsprogramexecutionCallerBecalledFunctioncallFunctiondeclaration声明将调用该函数FunctiondefinitionWhenafunctionhasnoparameters,thewordvoidisplacedinparenthesesafterthefunction’sname(orjustleaveitempty):
voidprintsomething(){
…..}Toindicatethatafunctionhasnoreturnvalue,wespecifythatitsreturntypeisvoid.void
isatypewithnovalues.Tocallafunctionwithnoarguments,wewritethefunction’sname,followedbyparentheses:
printsomething()//无参函数调用时括号是空的
Acallofprintsomething()mustappearinastatementbyitself:
printsomething();//无返回值函数调用必须是独立语句11FunctionDefinitionsGeneralformofafunctiondefinition:最简单的函数形式,无参数无返回值 void
function-name() {
declarations
statements }Call:function-name();//无返回值的函数调用,是一个独立句子12Classassignment29:Writefunctionvoidfun_family()toprintamessagetoyourfamily.(oranythinguwant)Callyourfunctioninmain()13voidfun_family(){printf(“Mom,Iwantanice-cream!\n");}Functioncanbecalledasmanytimesasneededasshownforfunction_2(…).Canbecalledinanyorder.14Classassignment30:Writefunctionvoidfun_1()toprintwhereareufrom.Writefunctionvoidfun_2()toprint“IloveChina(oryourcountry)!”.Writefunctionvoidfun_3()toprint“IwillbethebeststudentofNWPU!!”.FirstCallfun_1onetime,thencallfun_2twotimes,finallycallfun_3threetimes.15Classassignment31:Writefunctionvoidheart()toprintaheart.-1.5<=x<=1.5;-1.5<=y<=1.516#include<math.h>#include<windows.h>#include<WinBase.h>Thepointsontheheartcurvesatisfythiscurveequation6.3Arguments17无返回值有形式参数 void
function-name(parameters) {
declarations
statements }Call:function-name(Arguments);函数调用,无返回值则用独立句子调用;有形参parameters,调用时要给出实参Arguments;而且Arguments的值会传递给parameters18②Thesecondformofafunctiondefinition6.3ArgumentsInC,argumentsarepassedbyvalue:
参数传递whenafunctioniscalled,eachargumentisevaluatedanditsvalueassignedtothecorrespondingparameter.函数调用时,实参Argument把值复制给形参parameter,等价于赋值。ArgumentparameterParameter=ArgumentSum=add(a,b);Sum=add(3,5);Callowsfunctioncallsinwhichthetypesoftheargumentsdon’tmatchthetypesoftheparameters.196.3ArgumentsHowtopassargumentstoafunctions?Argument
ParametervoidaddNumbers(inta,intb) { intsum;
sum=a+b; printf(“%d\n”,sum); }Parameters
voidaddNumbers(inta,intb);addNumbers(n1,n2);Arguments
addNumbers(n1,n2);isacalloftheaddNumbers
function.Afunctioncallconsistsofafunctionnamefollowedbyalistofarguments.Argumentsareusedtosupplyinformationtoafunction.ThecalladdNumbers(n1,n2);causesthevaluesofn1,n2becopiedintotheparametera,b.Anargumentdoesn’thavetobeavariable;anyexpressionofatypewilldo.compatibleaddNumbers(n1,n2);andaddNumbers(3,5);arelegal.21#include<stdio.h>#include<stdlib.h>voidevenorodd(intm);voidevenorodd(intm){
if(m%2==0)printf("Even\n");
elseprintf("Odd\n");}intmain(){
intn;scanf("%d",&n);evenorodd(n);return0;}FunctioncallnmArgumentsParameters6.4ThereturnStatement
23③ThemostcomplexFunctionDefinitions24
return-type
function-name(parameters)最复杂的函数形式,既有返回值,又有形参 {
declarations
statementsreturn……..; }CALL:variable=function-name(arguments);有形参parameters,意味着调用时要给出实参Arguments,而且Arguments的值会传递给parameters;有返回值,则函数调用可以出现在任何要用返回值的地方ReturnTypeThereturntypeofafunctionisthetypeofvaluethatthefunctionreturns.Rulesgoverningthereturntype:Functionsmaynotreturnarrays.Specifyingthatthereturntypeisvoidindicatesthatthefunctiondoesn’treturnavalue.25FunctionDefinitionsreturn-type
function-name(parameters) {
declarations
statements }doubleadd(doublea,doubleb) { doublesum;
sum=a+b; returnsum; }CALL:Example1:total=add(x,y);Example2:if(add(x,y)<0)printf("Sumisnegitive\n");Example3:printf("Thesumis%f\n",add(x,y));Theworddoubleatthebeginningisthereturntypeofadd.
Executingfunctionbodycausesthefunctionto“return”totheplacefromwhichitwascalled;thevalueofsumwillbethevaluereturnedbythefunction.返回值会返回到函数调用的地方。所以,通常把函数调用写在需要用返回值的地方。比如赋值语句或者输出语句。We’llputthecallofaddintheplacewhereweneedtousethereturnvalue.Astatementthatcopythesumto
total:
total=add(x,y);返回值返回到这里,用来赋值。27DefiningandCallingFunctions#include<stdio.h>doubleaverage(doublex,doubley) {
return(x+y)/2; }intmain(){………..K1=average(3,5);
………..}Callingafunction//withareturnvalueandparametersArguments
Parameters
K1=average(3,5);K2=average(a,b);K3=average(a/2,
b/2);printf("%f\n",average(a,b));30#include<stdio.h>
doubleaverage(doublea,doubleb);/*DECLARATION*/
intmain(){doublex,y,z;scanf("%lf%lf%lf",&x,&y,&z);printf("Averageof%fand%f:%f\n",x,y,average(x,y));printf("Averageof%fand%f:%f\n",y,z,average(y,z));printf("Averageof%fand%f:%f\n",x,z,average(x,z));return0;}doubleaverage(doublea,doubleb)/*DEFINITION*/{return(a+b)/2;}Classassignment32:Writeafunctionintadd(intx,inty).input2integersandtheoperator,calladdfunctionandreturnthesumtomain.outputtheresultinmain(NOTinaddfunction).Inputsample:3+5Outputsample:3+5=8HINT:scanf(“%d%c%d”,&a,&op,&b);3+5printf("%d%c%d=%d\n",a,op,b,add(a,b));31FunctionCallsAcallofavoid
functionisalwaysfollowedbyasemicolontoturnitintoastatement: print_count(i); printsomething();Acallofanon-void
functionproducesavaluethatcanbestoredinavariable,tested,printed,orusedinsomeotherway:
avg=average(x,y); if(average(x,y)>0) printf("Averageispositive\n"); printf("Theaverageis%g\n",average(x,y));32voidprintsomething(){printf("Iamafunction!");}6.4ThereturnStatementAnon-voidfunctionmustusethereturn
statementtospecifywhatvalueitwillreturn.afunctioncan’treturntwonumbersThereturnstatementhastheform
returnexpression;Theexpressionisoftenjustaconstantorvariable: return0; returnstatus;Morecomplexexpressionsarepossible: returna>=b?a:b;if(a>b)returna;elsereturnb;336.4ThereturnStatementIfthetypeoftheexpressioninareturn
statementdoesn’tmatchthefunction’sreturntype,theexpressionwillbeimplicitlyconvertedtothereturntype.Ifafunctionreturnsanint,butthereturn
statementcontainsadouble
expression,thevalueoftheexpressionisconvertedtoint.intfunc(){…return3.6;//3}346.5FunctionDeclarationsC99hasadoptedtherulethateitheradeclarationoradefinitionofafunctionmustbepresentpriortoanycallofthefunction.调用函数前必须声明。356.5FunctionDeclarationsdeclareeachfunctionbeforecallingit.Generalformofafunctiondeclaration(prototype):
return-type
function-name(parameters);doubleaverage(doublea,doubleb);
36Classassignment33:Writeasimple
calculator(4functions)doubleaddition(doublex,doubley)doublesubtraction(doublex,doubley)doublemultiplication(doublex,doubley)doubledivision(doublex,doubley)Input2numbersandtheoperator,callfunctionsandreturntheresulttomain.Outputtheresultinmain(NOTinuser-definedfunctions).Ifuenter3*5,thenushouldcallmultiplication.Ifuenter3/5,thenushouldcalldivisionInputsample:3*5 Inputsample:3/5Outputsample:3*5=15.000000 Outputsample:3/5=0.600000HINT:doublea,b;charop;scanf(“%lf%c%lf”,&a,&op,&b);if(op==‘*’)
printf("%f%c%f=%f\n",a,op,b,multiplication(a,b));376.6ArrayArgumentsWhenafunctionparameterisaone-dimensionalarray,thelengthofthearraycanbeleftunspecified:
intf(inta[])/*nolengthspecified*/ { … }Cdoesn’tprovideanyeasywayforafunctiontodeterminethelengthofanarraypassedtoit.Instead,we’llhavetosupplythelength—ifthefunctionneedsit—asanadditionalargument.386.6ArrayArgumentsExample: intaverage(inta[],intn) { inti,sum=0;
for(i=0;i<n;i++) sum+=a[i];
returnsum/n; }Sinceaverageneedstoknowthelengthofa,wemustsupplyitasasecondargument.396.6ArrayArgumentsTheprototypeforaveragehasthefollowingappearance:
intaverage(inta[],intn);406.6ArgumentsWhenaverageiscalled,thefirstargumentwillbethenameofanarray,andthesecondwillbeitslength:
intmain() { intb[100],avg; … avg=average(b,100); … }Noticethatwedon’tputbracketsafteranarraynamewhenpassingittoafunction:
total=average(b[100],100);/***WRONG***/41b[0]b[1]………b[99]baddress42 intaverage(inta[],intn) { inti,sum=0;
for(i=0;i<n;i++) sum+=a[i];
returnsum/n; }intmain() { intb[100],avg; … avg=average(b,100); … }b[0]a[0]b[1]a[1]………………b[99]a[99]baddressa100Classassignment34:Writeafunctionintsum_array(inta[],intn)inmain:inputanarraywith5elements;callsum_arrayfunctionandreturnthesumtomain;outputthesuminmain(NOTinsum_arrayfunction).Inputsample:351511Outputsample:2543intsum_array(inta[],intn);intsum_array(inta[],intn) { inti,sum=0;
for(i=0;i<n;i++) sum+=a[i];
returnsum; }intmain(){……..//declarationfor(i=0;i<5;i++)scanf("%d",&s[i]);sum=sum_array(s,5);
………//output}#include<stdio.h>#include<stdlib.h>intsum_array(inta[],intn);intsum_array(inta[],intn){inti,sum=0;for(i=0;i<n;i++)sum+=a[i];returnsum;}intmain(){inti,sum,b[5];for(i=0;i<5;i++)scanf("%d",&b[i]);sum=sum_array(b,5);printf("%d",sum);}//12345Classassignment35:Writeafunctiondoubleaverage(doublea[],intn)inmain:inputthearraywith5elements;callaveragefunctionandreturntheaveragetomain;outputtheresultinmain(NOTinaveragefunction).Inputsample:351511Outputsample:5.00000044doubleaverage(doublea[],intn);doubleaverage(doublea[],intn)
{
……….//calculatethesumreturn(sum/5);}intmain(){……..//declarationfor(i=0;i<5;i++)scanf("%lf",&s[i]);aver=average(s,5);
………//output}4545
例:定义求一维数组平均值的函数。doubleaverage(doublea[5]);doubleaverage(doublea[5])/*形参数组*/{inti;doublesum=0;for(i=0;i<5;i++)sum=sum+a[i];return(sum/5);}intmain(){inti;doubleaver,s[5];for(i=0;i<5;i++)scanf("%lf",&s[i]);aver=average(s);
/*数组名作实参*/printf("aver=%-7.2f\n",aver);}6.6ArrayArgumentsAfunctionhasnowaytocheckthatwe’vepasseditthecorrectarraylength.Wecanexploitthisfactbytellingthefunctionthatthearrayissmallerthanitreallyis.Supposethatwe’veonlystored50numbersinthebarray,eventhoughitcanhold100.Wecansumjustthefirst50elementsbywriting
total=sum_array(b,50);46Classassignment36:Writeafunctionintsum_array(inta[],intn)inmain:inputanarraywith10elements;callsum_arrayfunctionandreturnthesumofalltheelementstomain;callsum_arrayfunctionagainandreturnthesumofhalfofthearraytomain;outputtheresultsinmain(NOTinsum_arrayfunction).Inputsample:351511351511Outputsample:502547intsum_array(inta[],intn);intsum_array(inta[],intn) { inti,sum=0;
for(i=0;i<n;i++) sum+=a[i];
returnsum; }intmain(){……..//declarationfor(i=0;i<N;i++)scanf("%d",&b[i]);sum1=sum_array(b,10);sum2=sum_array(b,5);
………//output}6.6ArrayArgumentsIfaparameterisamultidimensionalarray,onlythelengthofthefirstdimensionmaybeomitted.Ifwerevisesum_arraysothataisatwo-dimensionalarray,wemustspecifythenumberofcolumnsina:
intsum_two_dimensional_array(inta[][10],intn) { inti,j,sum=0;
for(i=0;i<n;i++) for(j=0;j<10;j++) sum+=a[i][j];
returnsum; }486.7RecursionAfunctionisrecursiveifitcallsitself.Thefollowingfunctioncomputesn!(factorial)recursively,usingtheformulan!=n×(n–1)!: intfact(intn) { if(n<=1) return1; else returnn*fact(n-1); }495050Recursion:n!=n*(n-1)!(n>1)
3!=3*2!2
2!=2*1!11!=15151递归过程动态分配图示:┇
┇Callfact(1):f=1;Callfact(2):f=2*f(2-1);Callfact(3):f=3*f(3-1);452456460464468472476480484126f:
n:3f:
n:2f:
n:1主调:fact(3)分配释放discardRecursion递归法5252y=fact(3);Printyf=3*fact(2);return(f);f=1;return(f);f=2*fact(1);return(f);312261MaincallfactFactcallfactFactcallfactFactcallfact6.7RecursionToseehowrecursionworks,let’stracetheexecutionofthestatement i=fact(3); fact(3)findsthat3isnotlessthanorequalto1,soitcalls
fact(2),whichfindsthat2isnotlessthanorequalto1,so
itcalls
fact(1),whichfindsthat1islessthanorequalto1,soit
returns1,causing
fact(2)toreturn2×1=2,causing fact(3)toreturn3×2=6.53intfact(intn){if(n<=1)return1;elsereturnn*fact(n-1); }intfact(intn){if(n<=1)return1;elsereturnn*fact(n-1); }intfact(intn){if(n<=1)return1;elsereturnn*fact(n-1); }Recursionintfact(intn){
if(n<=1)
return1;
else
returnn*fact(n-1);}intfact(intn){
if(n<=1)
return1;
else
returnn*fact(n-1);}intfact(intn){
if(n<=1)
return1;
else
returnn*fact(n-1);}n:3n:1n:23*fact(2)2*fact(1)1factorial=fact(3);26fact(1)fact(2)6.8SortAlgorithm-----selectionsort55Theselectionsortalgorithmsortsanarraybyrepeatedlyfindingtheminimumelement(consideringascendingorder)fromunsortedpartandputtingitatthebeginning.
A[0]A[1]A[2]A[3]A[4]A[5]A[6]
voidSelectionSort(intA[],intn)
{
inti,j,min,t;
for(i=0;i<n-1;i++){//repeatn-1times
min=i;//setthefirstunsortedelementasminimum
for(j=i+1;j<n;j++)//foreachoftheunsortedelements
if(A[j]<A[min])//ifelement<currentminimum min=j;//settheelementasnewminimum//swapminimumwithfirstunsortedposition
if(i!=min)//if
theyareNOTatthecorrectposition
t=A[i],A[i]=A[min],A[min]=t;
}
}5657Round1Round2Round3Round4Round5Round6Classassignment37:SelectionSortWriteafunctionvoidSelectionSort(intA[],intn)inmain:inputthearraywith5elements;callSelectionSortfunction;outputthesortedarrayinmain.Inputsample:351511Outputsample:13551158
voidSelectionSort(intA[],intn)
{
inti,j,min,t;
for(i=0;i<n-1;i++){//repeatn-1times
min=i;//setthefirstunsortedelementasminimum
for(j=i+1;j<n;j++)//foreachoftheunsortedelements
if(A[j]<A[min])//ifelement<currentminimum min=j;//settheelementasnewminimum//swapminimumwithfirstunsortedposition
if(i!=min)//if
theyareNOTatthecorrectposition
t=A[i],A[i]=A[min],A[min]=t;
}
}BubbleSort59BubbleSortisthesimplestsortingalgorithmthatworksbyrepeatedlyswappingtheadjacentelementsiftheyareinwrongorder.A[0]A[1]A[2]A[3]A[4]A[5]A[6]comparesthefirsttwoelements,andswapssince48>30.
for(j=0;j<N-1;j++)//repeatn-1times
//Startingwiththefirstelement(index=0),comparethecurrentelementwiththenextelementofthearray.for(i=0;i<N-1-j;i++)//Ifthecurrentelementisgreaterthanthenextelementif(A[i]>A[i+1])
t=A[i],A[i]=A[i+1],A[i+1]=t;//swapthem//Ifthecurrentelementislessthanthenextelement,movetothenextelement.60Classassignment38:
BubbleSortWriteafunctionvoidBubbleSort(intA[],intn)inmain:inputthearraywith5elements;callBubbleSortfunction;outputthesortedarrayinmain.Inputsample:351511Outputsample:135511616.9ProgramOrganization6.9.1Scope6.9.2LocalVariables&GlobalVariables626.9.1LocalVariablesAvariabledeclaredinthebodyofafunctionissaidtobelocaltothefunction:函数内部定义的变量是局部变量 intsum_digits(intn) { intsum=0;/*localvariable*/
while(n>0){ sum+=n%6.9; n/=10; }
returnsum; }636.9.1LocalVariablesDefaultpropertiesoflocalvariables:AutomaticstoragedurationStorageis“automatically”allocated
whentheenclosingfunctioniscalledanddeallocated
whenthefunctionreturns.BlockscopeAlocalvariableisvisiblefromitspointofdeclarationtotheendoftheenclosingfunctionbody.646.9.1LocalVariablesParametersParametershavethesameproperties
aslocalvariablesAutomaticstoragedurationBlockscopeTheonlydifferenceisthateachparameterisinitializedautomaticallywhenafunctioniscalled(bybeingassignedthevalueofthecorrespondingargument).656.9.1LocalVariablesSinceC99doesn’trequirevariabledeclarationstocomeatthebeginningofafunction,it’spossibleforalocalvariabletohaveaverysmallscope:666.9.1LocalVariablesStaticLocalVariablesIncludingstatic
inthedeclarationofalocalvariablecausesittohavestaticstorageduration.Avariablewithstaticstoragedurationhasapermanentstoragelocation,soitretainsitsvaluethroughouttheexecutionoftheprogram.Example: voidf(void) { staticinti;/*staticlocalvariable*/ … }Astaticlocalvariablestillhasblockscope,soit’snotvisibletootherfunctions.
67LocalVariables681#include<stdio.h>2intfun()3{//initializeonlyonce4
staticintm=0;//initializebeforefunctioncall
5//intn=0;6m++;//n++;7
returnm;//returnn;8}9intmain()10{11
inti;12
for(i=1;i<=3;i++)13printf("(%d)=%d\n",i,fun());14
return0;15}Demo:Times_Call.c6.9.2GlobalVariablesPassingargumentsisonewaytotransmitinformationtoafunction.FunctionscanalsocommunicatethroughexternalvariablesTheyarethevariablesthataredeclaredoutsidethebodyofanyfunction.Externalvariablesaresometimesknownasglobalvariables.69CProgrammingTutorial-55-GlobalvsLocalVariables6.9.2GlobalVariables701#include<stdio.h>2intcnt=0;3voidfun()
4{
5cnt++;6}7intmain()8{9inti,c;10for(i=1;i<=10;i++)
11fun();12printf("%d\n",cnt);13
return0;14}Demo:Times_Call2.c6.9.2GlobalVariablesPropertiesofexternalvariables:StaticstoragedurationFilescopeHavingfilescopemeansthatanexternalvariableisvisiblefromitspointofdeclarationtotheendoftheenclosingfile.716.9.2GlobalVariables721#include<stdio.h>2intm=100;
3intn;
4intmain()5{6
inta;7a=10+m+n;//a=10+100+08
return0;9}6.9.2GlobalVariablesProsandConsofExternalVariablesExternalvariablesareconvenientwhenmanyfunctionsmustshareavariableorwhenafewfunctionssharealargenumberofvariables.Inmostcases,it’sbetterforfunctionstocommunicatethroughparametersratherthanbysharingvariables:Ifwechangeanexternalvariableduringprogrammaintenance,we’llneedtocheckeveryfunctioninthesamefiletoseehowthechangeaffectsit.Ifanexternalvariableisassignedanincorrectvalue,itmaybedifficulttoidentifytheguiltyfunction.Functionsthatrelyonexternalvariablesarehardtoreuseinotherprograms.736.9.2GlobalVariablesProsandConsofExternalVariablesDon’tusethesameexternalvariablefordifferentpurposesindifferentfunctions.Supposethatseveralfunctionsneedavariablenameditocontrolaforstatement.Insteadofdeclaringiineachfunctionthatusesit,someprogrammersdeclareitjustonceatthetopoftheprogram.Thispracticeismisleading;someonereadingtheprogramlatermaythinkthattheusesofiarerelated,wheninfactthey’renot.Makesurethatexternalvariableshavemeaningfulnames.Localvariablesdon’talwaysneedmeaningfulnames:it’softenhardtothinkofabetternamethaniforthecontrolvariableinaforloop.746.9.2GlobalVariablesProsandConsofExternalVariablesMakingvariablesexternalwhentheyshouldbelocalcanleadtosomeratherfrustratingbugs.Codethatissupposedtodisplaya10×10arrangementofasterisks: inti; voidprint_one_row(void) { for(i=1;i<=10;i++) printf("*"); }
voidprint_all_rows(void) { for(i=1;i<=10;i++){ print_one_row(); printf("\n"); } }
Insteadofprinting10rows,print_all_rowsprintsonlyone.75BlocksInSection5.2,weencounteredcompoundstatementsoftheform {statements}Callowscompoundstatementstocontaindeclarationsaswellasstatements: {declarations
statements
}Thiskindofcompoundstatementiscalledablock.
76BlocksExampleofablock: if(i>j){/*swapvaluesofiandj*/ inttemp=i; i=j; j=temp; }temp=0;/*wrong*/77BlocksBydefault,thestoragedurationofavariabledeclaredinablockisautomatic:storageforthevariableisallocatedwhentheblockisenteredanddeallocatedwhentheblockisexited.Thevariablehasblockscope;itcan’tbereferencedoutsidetheblock.Avariablethatbelongstoablockcanbedeclaredstatictogiveitstaticstorageduration.78BlocksThebodyofafunctionisablock.Blocksarealsousefulinsideafunctionbodywhenweneedvariablesfortemporaryuse.Advantagesofdeclaringtemporaryvariablesinblocks:Avoidsclutteringdeclarationsatthebeginningofthefunctionbodywithvariablesthatareusedonlybriefly.Reducesnameconflicts.C99allowsvariablestobedeclaredanywherewithinablock.796.9.1ScopeInaCprogram,thesameidentifiermayhaveseveraldifferentmeanings.C’sscoperulesenabletheprogrammer(andthecompiler)todeterminewhichmeaningisrelevantatagivenpointintheprogram.Themostimportantscoperule:Whenadeclarationinsideablocknamesanidentifierthat’salreadyvisible,thenewdeclarationtemporarily“hides”theoldone,andtheidentifiertakesonanewmeaning.Attheendoftheblock,theidentifierregainsitsoldmeaning.80816.9.4ScopeIntheexampleonthenextsli
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 绩效管理和激励计划
- 班级自主管理的实施案例研究计划
- 2025年中国消毒灭菌设备行业市场运行态势、进出口贸易及发展趋势预测报告
- 企业战略规划与执行结构优化方案
- 电子支付系统安全测试的要点
- 2025年农林牧渔专用仪器仪表项目建议书
- 2025年NOX、NO2自动采样器及测定仪合作协议书
- 新产品使用指南及功能介绍
- 物理治疗课件
- 80天环游地球知识竞赛
- 一年级综合实践小小医院
- 电子商务客户服务(第2版)中职PPT完整全套教学课件
- 国家中小学智慧教育平台推动家校共育
- 部编版七年级语文下册全册教案设计(表格式)
- 《马克思主义与社会科学方法论》授课教案
- 船舶结构与货运PPT完整全套教学课件
- 《线性代数》课后习题答案
- 前交叉韧带损伤PPT
- 数学四年级下册口算题(每页60道直接打印)
- 学校领导干部上讲台开展思想政治教育的实施方案
- 三年级道德与法治下册第一单元我和我的同伴教材解读新人教版
评论
0/150
提交评论