C++程序設計英文課件:Ch6 Functions and an Introduction to Recursion_第1頁
C++程序設計英文課件:Ch6 Functions and an Introduction to Recursion_第2頁
C++程序設計英文課件:Ch6 Functions and an Introduction to Recursion_第3頁
C++程序設計英文課件:Ch6 Functions and an Introduction to Recursion_第4頁
C++程序設計英文課件:Ch6 Functions and an Introduction to Recursion_第5頁
已閱讀5頁,還剩241頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領

文檔簡介

16Functionsand

anIntroductionto

Recursion2OBJECTIVESInthischapteryou’lllearn:Toconstructprogramsmodularlyfromfunctions.TousecommonmathfunctionsavailableintheC++StandardLibrary.Tocreatefunctionswithmultipleparameters.Themechanismsforpassinginformationbetweenfunctionsandreturningresults.Howthefunctioncall/returnmechanismissupportedbythefunctioncallstackandactivationrecords.Touserandomnumbergenerationtoimplementgame-playingapplications.Howthevisibilityofidentifiersislimitedtospecificregionsofprograms.Towriteanduserecursivefunctions,i.e.,functionsthatcallthemselves.36.1 Introduction6.2 ProgramComponentsinC++6.3 MathLibraryFunctions6.4 FunctionDefinitionswithMultipleParameters6.5 FunctionPrototypesandArgumentCoercion6.6 C++StandardLibraryHeaderFiles6.7 CaseStudy:RandomNumberGeneration6.8 CaseStudy:GameofChanceandIntroducingenum

6.9 StorageClasses6.10 ScopeRules6.11 FunctionCallStackandActivationRecords6.12 FunctionswithEmptyParameterLists

46.13 InlineFunctions6.14 ReferencesandReferenceParameters6.15 DefaultArguments6.16 UnaryScopeResolutionOperator6.17 FunctionOverloading6.18 FunctionTemplates6.19 Recursion6.20 ExampleUsingRecursion:FibonacciSeries6.21 Recursionvs.Iteration6.22 (Optional)SoftwareEngineeringCaseStudy:IdentifyingClassOperationsintheATMSystem6.23 Wrap-Up

56.1IntroductionDivideandconquertechniqueConstructalargeprogramfromsmall,simplepieces(e.g.,components)FunctionsFacilitatethedesign,implementation,operationandmaintenanceoflargeprogramsC++StandardLibrarymathfunctions66.2ProgramComponentsinC++C++StandardLibraryRichcollectionoffunctionsforperformingcommonoperations,suchas:MathematicalcalculationsStringmanipulationsCharactermanipulationsInput/OutputErrorcheckingProvidedaspartoftheC++programmingenvironment7SoftwareEngineeringObservation6.1ReadthedocumentationforyourcompilertofamiliarizeyourselfwiththefunctionsandclassesintheC++StandardLibrary.86.2ProgramComponentsinC++(Cont.)FunctionsCalledmethodsorproceduresinotherlanguagesAllowprogrammerstomodularizeaprogrambyseparatingitstasksintoself-containedunitsStatementsinfunctionbodiesarewrittenonlyonceReusedfromperhapsseverallocationsinaprogramHiddenfromotherfunctions AvoidrepeatingcodeEnablethedivide-and-conquerapproachReusableinotherprogramsUser-definedorprogrammer-definedfunctions9SoftwareEngineeringObservation6.2Topromotesoftwarereusability,everyfunctionshouldbelimitedtoperformingasingle,well-definedtask,andthenameofthefunctionshouldexpressthattaskeffectively.Suchfunctionsmakeprogramseasiertowrite,test,debugandmaintain.10Error-PreventionTip6.1Asmallfunctionthatperformsonetaskiseasiertotestanddebugthanalargerfunctionthatperformsmanytasks.11SoftwareEngineeringObservation6.3Ifyoucannotchooseaconcisenamethatexpressesafunction’stask,yourfunctionmightbeattemptingtoperformtoomanydiversetasks.Itisusuallybesttobreaksuchafunctionintoseveralsmallerfunctions.126.2ProgramComponentsinC++(cont.)Function(Cont.)AfunctionisinvokedbyafunctioncallCalledfunctioneitherreturnsaresultorsimplyreturnstothecallerFunctioncallsformhierarchicalrelationships13Fig.6.1

|Hierarchicalbossfunction/workerfunctionrelationship.146.3MathLibraryFunctionsGlobalfunctionsDonotbelongtoaparticularclassHavefunctionprototypesplacedinheaderfilesCanbereusedinanyprogramthatincludestheheaderfileandthatcanlinktothefunction’sobjectcodeExample:sqrtin<cmath>headerfilesqrt(900.0)

Allfunctionsin<cmath>areglobalfunctions15Fig.6.2

|Mathlibraryfunctions.

166.4FunctionDefinitionswithMultipleParametersMultipleparametersFunctionsoftenrequiremorethanonepieceofinformationtoperformtheirtasksSpecifiedinboththefunctionprototypeandthefunctionheaderasacomma-separatedlistofparameters17OutlineGradeBook.h

(1of1)PrototypeforamemberfunctionthattakesthreeargumentsDatamembertostoremaximumgrade18OutlineGradeBook.cpp

(1of3)19OutlineGradeBook.cpp(2of3)Calltofunctionmaximumpassesthreearguments20OutlineGradeBook.cpp

(3of3)maximummemberfunctionheaderComma-separatedparameterlistReturningavaluetothecaller21Outlinefig06_05.cpp

(1of1)22SoftwareEngineeringObservation6.4Thecommasusedinline58ofFig.

6.4toseparatetheargumentstofunctionmaximumarenotcommaoperatorsasdiscussedinSection

5.3.Thecommaoperatorguaranteesthatitsoperandsareevaluatedlefttoright.Theorderofevaluationofafunction’sarguments,however,isnotspecifiedbytheC++standard.Thus,differentcompilerscanevaluatefunctionargumentsindifferentorders.TheC++standarddoesguaranteethatallargumentsinafunctioncallareevaluatedbeforethecalledfunctionexecutes.

236.4FunctionDefinitionswithMultipleParameters(Cont.)Compilerusesafunctionprototypeto:CheckthatcallstothefunctioncontainthecorrectnumberandtypesofargumentsinthecorrectorderEnsurethatthevaluereturnedbythefunctionisusedcorrectlyintheexpressionthatcalledthefunctionEachargumentmustbeconsistentwiththetypeofthecorrespondingparameterParametersarealsocalledformalparameters24PortabilityTip6.1Sometimeswhenafunction’sargumentsaremoreinvolvedexpressions,suchasthosewithcallstootherfunctions,theorderinwhichthecompilerevaluatestheargumentscouldaffectthevaluesofoneormoreofthearguments.Iftheevaluationorderchangesbetweencompilers,theargumentvaluespassedtothefunctioncouldvary,causingsubtlelogicerrors.25Error-PreventionTip6.2Ifyouhavedoubtsabouttheorderofevaluationofafunction’sargumentsandwhethertheorderwouldaffectthevaluespassedtothefunction,evaluatetheargumentsinseparateassignmentstatementsbeforethefunctioncall,assigntheresultofeachexpressiontoalocalvariable,thenpassthosevariablesasargumentstothefunction.26CommonProgrammingError6.1Declaringmethodparametersofthesametypeasdouble

x,

yinsteadofdouble

x,

double

yisasyntaxerror—anexplicittypeisrequiredforeachparameterintheparameterlist.27CommonProgrammingError6.2Compilationerrorsoccurifthefunctionprototype,functionheaderandfunctioncallsdonotallagreeinthenumber,typeandorderofargumentsandparameters,andinthereturntype.28SoftwareEngineeringObservation6.5Afunctionthathasmanyparametersmaybeperformingtoomanytasks.Considerdividingthefunctionintosmallerfunctionsthatperformtheseparatetasks.Limitthefunctionheadertoonelineifpossible.296.4FunctionDefinitionswithMultipleParameters(Cont.)Threewaystoreturncontroltothecallingstatement:Ifthefunctiondoesnotreturnaresult:Programflowreachesthefunction-endingrightbraceorProgramexecutesthestatementreturn;Ifthefunctiondoesreturnaresult:Programexecutesthestatementreturn

expression;expressionisevaluatedanditsvalueisreturnedtothecaller306.5FunctionPrototypesandArgumentCoercionFunctionprototypeAlsocalledafunctiondeclarationIndicatestothecompiler:NameofthefunctionTypeofdatareturnedbythefunctionParametersthefunctionexpectstoreceiveNumberofparametersTypesofthoseparametersOrderofthoseparameters31SoftwareEngineeringObservation6.6FunctionprototypesarerequiredinC++.Use#includepreprocessordirectivestoobtainfunctionprototypesfortheC++StandardLibraryfunctionsfromtheheaderfilesfortheappropriatelibraries(e.g.,theprototypeformathfunctionsqrtisinheaderfile<cmath>;apartiallistofC++StandardLibraryheaderfilesappearsinSection

6.6).Alsouse#includetoobtainheaderfilescontainingfunctionprototypeswrittenbyyouoryourgroupmembers.32CommonProgrammingError6.3Ifafunctionisdefinedbeforeitisinvoked,thenthefunction’sdefinitionalsoservesasthefunction’sprototype,soaseparateprototypeisunnecessary.Ifafunctionisinvokedbeforeitisdefined,andthatfunctiondoesnothaveafunctionprototype,acompilationerroroccurs.33SoftwareEngineeringObservation6.7Alwaysprovidefunctionprototypes,eventhoughitispossibletoomitthemwhenfunctionsaredefinedbeforetheyareused(inwhichcasethefunctionheaderactsasthefunctionprototypeaswell).Providingtheprototypesavoidstyingthecodetotheorderinwhichfunctionsaredefined(whichcaneasilychangeasaprogramevolves).346.5FunctionPrototypesandArgumentCoercion(Cont.)Functionsignature(orsimplysignature)TheportionofafunctionprototypethatincludesthenameofthefunctionandthetypesofitsargumentsDoesnotspecifythefunction’sreturntypeFunctionsinthesamescopemusthaveuniquesignaturesThescopeofafunctionistheregionofaprograminwhichthefunctionisknownandaccessible35CommonProgrammingError6.4Itisacompilationerroriftwofunctionsinthesamescopehavethesamesignaturebutdifferentreturntypes.366.5FunctionPrototypesandArgumentCoercion(Cont.)ArgumentCoercionForcingargumentstotheappropriatetypesspecifiedbythecorrespondingparametersForexample,callingafunctionwithanintegerargument,eventhoughthefunctionprototypespecifiesadoubleargumentThefunctionwillstillworkcorrectly376.5FunctionPrototypesandArgumentCoercion(Cont.)C++PromotionRulesIndicatehowtoconvertbetweentypeswithoutlosingdataApplytoexpressionscontainingvaluesoftwoormoredatatypesSuchexpressionsarealsoreferredtoasmixed-typeexpressionsEachvalueintheexpressionispromotedtothe“highest”typeintheexpressionTemporaryversionofeachvalueiscreatedandusedfortheexpressionOriginalvaluesremainunchanged386.5FunctionPrototypesandArgumentCoercion(Cont.)C++PromotionRules(Cont.)PromotionalsooccurswhenthetypeofafunctionargumentdoesnotmatchthespecifiedparametertypePromotionisasiftheargumentvaluewerebeingassigneddirectlytotheparametervariableConvertingavaluetoalowerfundamentaltypeWilllikelyresultinthelossofdataorincorrectvaluesCanonlybeperformedexplicitlyByassigningthevaluetoavariableoflowertype(somecompilerswillissueawarninginthiscase)orByusingacastoperator39Fig.6.6

|Promotionhierarchyforfundamentaldatatypes.

40CommonProgrammingError6.5Convertingfromahigherdatatypeinthepromotionhierarchytoalowertype,orbetweensignedandunsigned,cancorruptthedatavalue,causingalossofinformation.41CommonProgrammingError6.6Itisacompilationerroriftheargumentsinafunctioncalldonotmatchthenumberandtypesoftheparametersdeclaredinthecorrespondingfunctionprototype.Itisalsoanerrorifthenumberofargumentsinthecallmatches,buttheargumentscannotbeimplicitlyconvertedtotheexpectedtypes.426.6C++StandardLibraryHeaderFilesC++StandardLibraryheaderfilesEachcontainsaportionoftheStandardLibraryFunctionprototypesfortherelatedfunctionsDefinitionsofvariousclasstypesandfunctionsConstantsneededbythosefunctions“Instruct”thecompileronhowtointerfacewithlibraryanduser-writtencomponentsHeaderfilenamesendingin.hAre“old-style”headerfilesSupersededbytheC++StandardLibraryheaderfiles43Fig.6.7

|C++StandardLibraryheaderfiles.(Part1of4)

44Fig.6.7

|C++StandardLibraryheaderfiles.(Part2of4)

45Fig.6.7

|C++StandardLibraryheaderfiles.(Part3of4)

46Fig.6.7

|C++StandardLibraryheaderfiles.(Part4of4)

476.7CaseStudy:RandomNumberGenerationC++StandardLibraryfunctionrand

IntroducestheelementofchanceintocomputerapplicationsExamplei=rand();Generatesanunsignedintegerbetween0andRAND_MAX(asymbolicconstantdefinedinheaderfile<cstdlib>)Functionprototypefortherandfunctionisin<cstdlib>486.7CaseStudy:RandomNumberGeneration(Cont.)Toproduceintegersinaspecificrange,usethemodulusoperator(%)withrandExamplerand()%6;Producesnumbersintherange0to5Thisiscalledscaling,6isthescalingfactorShiftingcanmovetherangeto1to61+rand()%6;49Outlinefig06_08.cpp

(1of2)#includeandusingforfunctionrandCallingfunctionrand50Outlinefig06_08.cpp

(2of2)51Outlinefig06_09.cpp

(1of3)Scalingandshiftingthevalueproducedbyfunctionrand52Outlinefig06_09.cpp(2of3)53Outlinefig06_09.cpp

(3of3)Eachfacevalueappearsapproximately1,000,000times54Error-PreventionTip6.3Provideadefaultcaseinaswitchtocatcherrorsevenifyouareabsolutely,positivelycertainthatyouhavenobugs!556.7CaseStudy:RandomNumberGeneration(Cont.)Functionrand

GeneratespseudorandomnumbersThesamesequenceofnumbersrepeatsitselfeachtimetheprogramexecutesRandomizingConditioningaprogramtoproduceadifferentsequenceofrandomnumbersforeachexecutionC++StandardLibraryfunctionsrandTakesanunsignedintegerargumentSeedstherandfunctiontoproduceadifferentsequenceofrandomnumbers56Outlinefig06_10.cpp

(1of2)usingstatementforfunctionsrandDatatypeunsignedisshortforunsigned

intPassingseedtosrandtorandomizetheprogram57Outlinefig06_10.cpp

(2of2)Programoutputsshowthateachuniqueseedvalueproducesadifferentsequenceofrandomnumbers586.7CaseStudy:RandomNumberGeneration(Cont.)Torandomizewithouthavingtoenteraseedeachtimesrand(time(0));ThiscausesthecomputertoreaditsclocktoobtaintheseedvalueFunctiontime(withtheargument0)ReturnsthecurrenttimeasthenumberofsecondssinceJanuary1,1970atmidnightGreenwichMeanTime(GMT)Functionprototypefortimeisin<ctime>59CommonProgrammingError6.7Callingfunctionsrandmorethanonceinaprogramrestartsthepseudorandomnumbersequenceandcanaffecttherandomnessofthenumbersproducedbyrand.60CommonProgrammingError6.8Usingsrandinplaceofrandtoattempttogeneraterandomnumbersisacompilationerror—functionsranddoesnotreturnavalue.616.7CaseStudy:RandomNumberGeneration(Cont.)ScalingandshiftingrandomnumbersToobtainrandomnumbersinadesiredrange,useastatementlike

number=shiftingValue+rand()%scalingFactor;shiftingValueisequaltothefirstnumberinthedesiredrangeofconsecutiveintegersscalingFactorisequaltothewidthofthedesiredrangeofconsecutiveintegersnumberofconsecutiveintegersintherange626.8CaseStudy:GameofChanceandIntroducingenumEnumerationAsetofintegerconstantsrepresentedbyidentifiersThevaluesofenumerationconstantsstartat0,unlessspecifiedotherwise,andincrementby1Theidentifiersinanenummustbeunique,butseparateenumerationconstantscanhavethesameintegervalueDefininganenumerationKeywordenum

AtypenameComma-separatedlistofidentifiernamesenclosedinbracesExampleenumMonths{JAN=1,FEB,MAR,APR};63Outlinefig06_11.cpp

(1of4)#includeandusingforfunctiontimeEnumerationtokeeptrackofthegamestatusDeclaringavariableoftheuser-definedenumerationtypeSeedingtherandomnumbergeneratorwiththecurrenttime64Outlinefig06_11.cpp

(2of4)AssigninganenumerationconstanttogameStatusComparingavariableofanenumerationtypetoanenumerationconstant65Outlinefig06_11.cpp

(3of4)Functionthatperformsthetaskofrollingthedice66Outlinefig06_11.cpp

(4of4)67GoodProgrammingPractice6.1Capitalizethefirstletterofanidentifierusedasauser-definedtypename.68GoodProgrammingPractice6.2Useonlyuppercaselettersinthenamesofenumerationconstants.Thismakesthesecon-stantsstandoutinaprogramandremindstheprogrammerthatenumerationconstantsarenotvariables.69GoodProgrammingPractice6.3Usingenumerationsratherthanintegerconstantscanmakeprogramsclearerandmoremaintainable.Youcansetthevalueofanenumerationconstantonceintheenumerationdeclaration.70CommonProgrammingError6.9Assigningtheintegerequivalentofanenumerationconstanttoavariableoftheenumerationtypeisacompilationerror.71CommonProgrammingError6.10Afteranenumerationconstanthasbeendefined,attemptingtoassignanothervaluetotheenumerationconstantisacompilationerror.726.9StorageClassesEachidentifierhasseveralattributesName,type,sizeandvalueAlsostorageclass,scopeandlinkageC++providesfivestorage-classspecifiers:auto,register,extern,mutableandstaticIdentifier’sstorageclassDeterminestheperiodduringwhichthatidentifierexistsinmemoryIdentifier’sscopeDetermineswheretheidentifiercanbereferencedinaprogram736.9StorageClasses(Cont.)Identifier’slinkageDetermineswhetheranidentifierisknownonlyinthesourcefilewhereitisdeclaredoracrossmultiplefilesthatarecompiled,thenlinkedtogetherAnidentifier’sstorage-classspecifierhelpsdetermineitsstorageclassandlinkage746.9StorageClasses(Cont.)AutomaticstorageclassDeclaredwithkeywordsautoandregisterAutomaticvariablesCreatedwhenprogramexecutionentersblockinwhichtheyaredefinedExistwhiletheblockisactiveDestroyedwhentheprogramexitstheblockOnlylocalvariablesandparameterscanbeofautomaticstorageclassSuchvariablesnormallyareofautomaticstorageclass75PerformanceTip6.1Automaticstorageisameansofconservingmemory,becauseautomaticstorageclassvariablesexistinmemoryonlywhentheblockinwhichtheyaredefinedisexecuting.76SoftwareEngineeringObservation6.8Automaticstorageisanexampleoftheprincipleofleastprivilege,whichisfundamentaltogoodsoftwareengineering.Inthecontextofanapplication,theprinciplestatesthatcodeshouldbegrantedonlytheamountofprivilegeandaccessthatitneedstoaccomplishitsdesignatedtask,butnomore.Whyshouldwehavevariablesstoredinmemoryandaccessiblewhentheyarenotneeded?77PerformanceTip6.2Thestorage-classspecifierregistercanbeplacedbeforeanautomaticvariabledeclarationtosuggestthatthecompilermaintainthevariableinoneofthecomputer’shigh-speedhardwareregistersratherthaninmemory.Ifintenselyusedvariablessuchascountersortotalsaremaintainedinhardwareregisters,theoverheadofrepeatedlyloadingthevariablesfrommemoryintotheregistersandstoringtheresultsbackintomemoryiseliminated.786.9StorageClasses(Cont.)Storage-classspecifierauto

ExplicitlydeclaresvariablesofautomaticstorageclassLocalvariablesareofautomaticstorageclassbydefaultSokeywordautorarelyisusedStorage-classspecifierregisterDatainthemachine-languageversionofaprogramisnormallyloadedintoregistersforcalculationsandotherprocessingCompilertriestostoreregisterstorageclassvariablesinaregisterThecompilermightignoreregisterdeclarationsMaynotbesufficientregistersforthecompilertouse79CommonProgrammingError6.11Usingmultiplestorage-classspecifiersforanidentifierisasyntaxerror.Onlyonestorageclassspecifiercanbeappliedtoanidentifier.Forexample,ifyouincluderegister,donotalsoincludeauto.80PerformanceTip6.3Often,registerisunnecessary.Today’soptimizingcompilersarecapableofrecognizingfrequentlyusedvariablesandcandecidetoplacetheminregisterswithoutneedingaregisterdeclarationfromtheprogrammer.816.9StorageClasses(Cont.)StaticstorageclassDeclaredwithkeywordsexternandstaticStatic-storage-classvariablesExistfromthepointatwhichtheprogrambeginsexecutionInitializedoncewhentheirdeclarationsareencounteredLastforthedurationoftheprogramStatic-storage-classfunctionsThenameofthefunctionexistswhentheprogrambeginsexecution,justasforallotherfunctionsHowever,eventhoughthevariablesandthefunctionnamesexistfromthestartofprogramexecution,thisdoesnotmeanthattheseidentifierscanbeusedthroughouttheprogram.826.9StorageClasses(Cont.)TwotypesofidentifierswithstaticstorageclassExternalidentifiersSuchasglobalvariablesandglobalfunctionnamesLocalvariablesdeclaredwiththestorageclassspecifierstaticGlobalvariablesCreatedbyplacingvariabledeclarationsoutsideanyclassorfunctiondefinitionRetaintheirvaluesthroughouttheexecutionoftheprogramCanbereferencedbyanyfunctionthatfollowstheirdeclarationsordefinitionsinthesourcefile83SoftwareEngineeringObservation6.9Declaringavariableasglobalratherthanlocalallowsunintendedsideeffectstooccurwhenafunctionthatdoesnotneedaccesstothevariableaccidentallyormaliciouslymodifiesit.Thisisanotherexampleoftheprincipleofleastprivilege.Ingeneral,exceptfortrulyglobalresourcessuchascinandcout,theuseofglobalvariablesshouldbeavoidedexceptincertainsituationswithuniqueperformancerequirements.84SoftwareEngineeringObservation6.10Variablesusedonlyinaparticularfunctionshouldbedeclaredaslocalvariablesinthatfunctionratherthanasglobalvariables.856.9StorageClasses(Cont.)LocalvariablesdeclaredwithkeywordstaticKnownonlyinthefunctioninwhichtheyaredeclaredRetaintheirvalueswhenthefunctionreturnstoitscallerNexttimethefunctioniscalled,thestaticlocalvariablescontainthevaluestheyhadwhenthefunctionlastcompletedIfnumericvariablesofthestaticstorageclassarenotexplicitlyinitializedbytheprogrammerTheyareinitializedtozero866.10ScopeRulesScopePortionoftheprogramwhereanidentifiercanbeusedFourscopesforanidentifierFunctionscopeFilescopeBlockscopeFunction-prototypescope876.10ScopeRules(Cont.)FilescopeForanidentifierdeclaredoutsideanyfunctionorclassSuchanidentifieris“known”inallfunctionsfromthepointatwhichitisdeclareduntiltheendofthefileGlobalvariables,functiondefinitionsandfunctionprototypesplacedoutsideafunctionallhavefilescopeFunctionscopeLabels(identifiersfollowedbyacolonsuchasstart:)aretheonlyidentifierswithfunctionscopeCanbeusedanywhereinthefunctioninwhichtheyappearCannotbereferencedoutsidethefunctionbodyLabelsareimplementationdetailsthatfunctionshidefromoneanother886.10ScopeRules(Cont.)BlockscopeIdentifiersdeclaredinsideablockhaveblockscopeBlockscopebeginsattheidentifier’sdeclarationBlockscopeendsattheterminatingrightbrace(})oftheblockinwhichtheidentifierisdeclaredLocalvariablesandfunctionparametershaveblockscopeThefunctionbodyistheirblockAnyblockcancontainvariabledeclarationsIdentifiersinanouterblockcanbe“hidden”whenanestedblockhasalocalidentifierwiththesamenameLocalvariablesdeclaredstaticstillhaveblockscope,eventhoughtheyexistfromthetimetheprogrambeginsexecutionStoragedurationdoesnotaffectthescopeofanidentifier896.10ScopeRules(Cont.)Function-prototypescopeOnlyidentifiersusedintheparameterlistofafunctionprototypehavefunction-prototypescopeParameternamesappearinginafunctionprototypeareignoredbythecompilerIdentifiersusedinafunctionprototypecanbereusedelsewhereintheprogramwithoutambiguityHowever,inasingleprototype,aparticularidentifiercanbeusedonlyonce90CommonProgrammingError6.12Accidentallyusingthesamenameforanidentifierinaninnerblockthatisusedforanidentifierinanouterblock,wheninfacttheprogrammerwantstheidentifierintheouterblocktobeactiveforthedurationoftheinnerblock,isnormallyalogicerror.91GoodProgrammingPractice6.4Avoidvariablenamesthathidenamesinouterscopes.Thiscanbeaccomplishedbyavoidingtheuseofduplicateidentifiersinaprogram.92Outlinefig06_12.cpp

(1of4)DeclaringaglobalvariableoutsideanyclassorfunctiondefinitionLocalvariablexthathidesglobalvariablexLocalvariablexinablockthathideslocalvariablexinouterscope93Outlinefig06_12.cpp(2of4)LocalvariablethatgetsrecreatedandreinitializedeachtimeuseLocaliscalled94Outlinefig06_12.cpp

(3of4)staticlocalvariablethatgetsinitializedonlyonceStatementreferstoglobalvariablexbecausenolocalvariablenamedxexists95Outlinefig06_12.cpp

(4of4)966.11FunctionCallStackandActivationRecordsDatastructure:collectionofrelateddataitemsStackdatastructureAnalogoustoapileofdishesWhenadishisplacedonthepile,itisnormallyplacedatthetopReferredtoaspushingthedishontothestackSimilarly,whenadishisremovedfromthepile,itisnormallyremovedfromthetopReferredtoaspoppingthedishoffthestackAlast-in,first-out(LIFO)datastructureThelastitempushed(inserted)onthestackisthefirstitempopped(removed)fromthestack976.11FunctionCallStackandActivationRecords(Cont.)FunctionCallStackSometimescalledtheprogramexecutionstackSupportsthefunctioncall/returnmechanismEachtimeafunctioncallsanotherfunction,astackframe(alsoknownasanactivationrecord)ispushedontothestackMaintainsthereturnaddressthatthecalledfunctionneedstoreturntothecallingfunctionContainsautomaticvariables—parametersandanylocalvariablesthefunctiondeclares986.11FunctionCallStackandActivationRecords(Cont.)FunctionCallStack(Cont.)WhenthecalledfunctionreturnsStackframeforthefunctioncallispoppedControltransferstothereturnaddressinthepoppedstackframeIfafunctionmakesacalltoanotherfunctionStackframeforthenewfunctioncallissimplypushedontothecallstackRet

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
  • 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論