版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 物料搬運設備的能效提升與節(jié)能減排-洞察分析
- 營養(yǎng)素對頸部燒傷后傷口愈合的促進-洞察分析
- 文化金融產(chǎn)品體系構建-洞察分析
- 網(wǎng)紅經(jīng)濟效應評估-洞察分析
- 《SIYB中國項目介紹》課件
- 勤儉節(jié)約的精彩講話稿(12篇)
- 辦公空間設計的多元素文化融合與創(chuàng)新
- 健康飲食文化在家庭教育中的傳播與影響研究
- 2025簡單采購合同范本
- 關于孩子在競爭環(huán)境下自信心建立的研究
- 2024年甘肅定西渭源縣糧食和物資儲備中心選調2人歷年(高頻重點復習提升訓練)共500題附帶答案詳解
- 2024年6月浙江省高考地理試卷真題(含答案)
- 2024年越南分布式光伏發(fā)電行業(yè)現(xiàn)狀及前景分析2024-2030
- 高一物理運動學經(jīng)典例題
- 傷口造口護理質量標準
- Office辦公軟件理論知識考核試卷
- 客戶關系管理-課后練習參考答案 蘇朝暉
- JGJT334-2014 建筑設備監(jiān)控系統(tǒng)工程技術規(guī)范
- 可持續(xù)金融智慧樹知到期末考試答案章節(jié)答案2024年南昌大學
- 2024年網(wǎng)格員考試題庫1套
- 物流配送中心租賃合同
評論
0/150
提交評論