




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 病歷分析考試題庫(kù)及答案
- 中班健康課件《我長(zhǎng)大了》
- 八省聯(lián)考試題及答案曝光
- 中式盤花課件視頻
- 中山大學(xué)介紹
- plc編程及應(yīng)用考試題庫(kù)及答案
- 硅植物生長(zhǎng)促進(jìn)-洞察及研究
- 中班健康水果本領(lǐng)大課件
- 兒茶酸皮膚光老化干預(yù)-洞察及研究
- 2025-2030中國(guó)瀝青乳化設(shè)備行業(yè)市場(chǎng)需求分析及發(fā)展趨勢(shì)與投資價(jià)值研究報(bào)告
- 直流屏原理-課件
- 加藥設(shè)備安裝 檢驗(yàn)批施工質(zhì)量驗(yàn)收表
- 崗位技能評(píng)定機(jī)考考場(chǎng)規(guī)則
- 盡職調(diào)查所用相關(guān)表格(全)
- 三基-學(xué)校兒童少年衛(wèi)生學(xué)(200題)練習(xí)
- 老年康養(yǎng)服務(wù)中心項(xiàng)目可行性研究報(bào)告寫作參考范文
- 生物質(zhì)中纖維素、半纖維素和木質(zhì)素含量的測(cè)定
- 枸杞采摘合同
- 渦流探傷儀設(shè)計(jì)方案
- 張家界船舶工業(yè)項(xiàng)目建議書【模板范本】
- 來(lái)料檢驗(yàn)報(bào)告模板
評(píng)論
0/150
提交評(píng)論