C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 6 Functions、Chapter 7 Pointers_第1頁
C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 6 Functions、Chapter 7 Pointers_第2頁
C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 6 Functions、Chapter 7 Pointers_第3頁
C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 6 Functions、Chapter 7 Pointers_第4頁
C程序設(shè)計(jì)基礎(chǔ) 英文版 課件 Chapter 6 Functions、Chapter 7 Pointers_第5頁
已閱讀5頁,還剩146頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

Chapter6Functions函數(shù)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沒有參數(shù),沒有返回值的函數(shù)#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用戶自定義的函數(shù)只能通過函數(shù)調(diào)用的方式執(zhí)行。沒有被調(diào)用,它就不會(huì)被執(zhí)行//functionmainbeginsprogramexecutionCallerBecalledFunctioncallFunctiondeclaration聲明將調(diào)用該函數(shù)FunctiondefinitionWhenafunctionhasnoparameters,thewordvoidisplacedinparenthesesafterthefunction’sname(orjustleaveitempty):

voidprintsomething(){

…..}Toindicatethatafunctionhasnoreturnvalue,wespecifythatitsreturntypeisvoid.void

isatypewithnovalues.Tocallafunctionwithnoarguments,wewritethefunction’sname,followedbyparentheses:

printsomething()//無參函數(shù)調(diào)用時(shí)括號(hào)是空的

Acallofprintsomething()mustappearinastatementbyitself:

printsomething();//無返回值函數(shù)調(diào)用必須是獨(dú)立語句11FunctionDefinitionsGeneralformofafunctiondefinition:最簡(jiǎn)單的函數(shù)形式,無參數(shù)無返回值 void

function-name() {

declarations

statements }Call:function-name();//無返回值的函數(shù)調(diào)用,是一個(gè)獨(dú)立句子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無返回值有形式參數(shù) void

function-name(parameters) {

declarations

statements }Call:function-name(Arguments);函數(shù)調(diào)用,無返回值則用獨(dú)立句子調(diào)用;有形參parameters,調(diào)用時(shí)要給出實(shí)參Arguments;而且Arguments的值會(huì)傳遞給parameters18②Thesecondformofafunctiondefinition6.3ArgumentsInC,argumentsarepassedbyvalue:

參數(shù)傳遞whenafunctioniscalled,eachargumentisevaluatedanditsvalueassignedtothecorrespondingparameter.函數(shù)調(diào)用時(shí),實(shí)參Argument把值復(fù)制給形參parameter,等價(jià)于賦值。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)最復(fù)雜的函數(shù)形式,既有返回值,又有形參 {

declarations

statementsreturn……..; }CALL:variable=function-name(arguments);有形參parameters,意味著調(diào)用時(shí)要給出實(shí)參Arguments,而且Arguments的值會(huì)傳遞給parameters;有返回值,則函數(shù)調(diào)用可以出現(xiàn)在任何要用返回值的地方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.返回值會(huì)返回到函數(shù)調(diào)用的地方。所以,通常把函數(shù)調(diào)用寫在需要用返回值的地方。比如賦值語句或者輸出語句。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.調(diào)用函數(shù)前必須聲明。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

例:定義求一維數(shù)組平均值的函數(shù)。doubleaverage(doublea[5]);doubleaverage(doublea[5])/*形參數(shù)組*/{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);

/*數(shù)組名作實(shí)參*/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遞歸過程動(dòng)態(tài)分配圖示:┇

┇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主調(diào):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:函數(shù)內(nèi)部定義的變量是局部變量 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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論