程序设计语言概念(ConceptsofProgramming-Languages)-英文-第10版第课件_第1页
程序设计语言概念(ConceptsofProgramming-Languages)-英文-第10版第课件_第2页
程序设计语言概念(ConceptsofProgramming-Languages)-英文-第10版第课件_第3页
程序设计语言概念(ConceptsofProgramming-Languages)-英文-第10版第课件_第4页
程序设计语言概念(ConceptsofProgramming-Languages)-英文-第10版第课件_第5页
已阅读5页,还剩81页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

Chapter5Names,Bindings,andScopesChapter5Names,Bindings,andChapter5TopicsIntroductionNamesVariablesTheConceptofBindingScopeScopeandLifetimeReferencingEnvironmentsNamedConstants2Copyright©2012Addison-Wesley.Allrightsreserved.Chapter5TopicsIntroduction2IntroductionImperativelanguagesareabstractionsofvonNeumannarchitectureMemoryProcessorVariablesarecharacterizedbyattributesTodesignatype,mustconsiderscope,lifetime,typechecking,initialization,andtypecompatibility3Copyright©2012Addison-Wesley.Allrightsreserved.IntroductionImperativelanguagNamesDesignissuesfornames:Arenamescasesensitive?Arespecialwordsreservedwordsorkeywords?4Copyright©2012Addison-Wesley.Allrightsreserved.NamesDesignissuesfornames:4Names(continued)LengthIftooshort,theycannotbeconnotativeLanguageexamples:FORTRAN95:maximumof31C99:nolimitbutonlythefirst63aresignificant;also,externalnamesarelimitedtoamaximumof31C#,Ada,andJava:nolimit,andallaresignificantC++:nolimit,butimplementersoftenimposeone5Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)Length5CopyriNames(continued)SpecialcharactersPHP:allvariablenamesmustbeginwithdollarsignsPerl:allvariablenamesbeginwithspecialcharacters,whichspecifythevariable’stypeRuby:variablenamesthatbeginwith@areinstancevariables;thosethatbeginwith@@areclassvariables6Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)SpecialcharaNames(continued)CasesensitivityDisadvantage:readability(namesthatlookalikearedifferent)NamesintheC-basedlanguagesarecasesensitiveNamesinothersarenotWorseinC++,Java,andC#becausepredefinednamesaremixedcase(e.g.IndexOutOfBoundsException)7Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)CasesensitivNames(continued)SpecialwordsAnaidtoreadability;usedtodelimitorseparatestatementclausesAkeywordisawordthatisspecialonlyincertaincontexts,e.g.,inFortranRealVarName

(Realisadatatypefollowedwithaname,thereforeRealisakeyword)Real=3.4

(Realisavariable) Areservedwordisaspecialwordthatcannotbeusedasauser-definednamePotentialproblemwithreservedwords:Iftherearetoomany,manycollisionsoccur(e.g.,COBOLhas300reservedwords!)8Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)SpecialwordsVariablesAvariableisanabstractionofamemorycellVariablescanbecharacterizedasasextupleofattributes:NameAddressValueTypeLifetimeScope9Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAvariableisanabstVariablesAttributesName-notallvariableshavethemAddress-thememoryaddresswithwhichitisassociatedAvariablemayhavedifferentaddressesatdifferenttimesduringexecutionAvariablemayhavedifferentaddressesatdifferentplacesinaprogramIftwovariablenamescanbeusedtoaccessthesamememorylocation,theyarecalledaliasesAliasesarecreatedviapointers,referencevariables,CandC++unionsAliasesareharmfultoreadability(programreadersmustrememberallofthem)10Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAttributesName-notVariablesAttributes(continued)Type-determinestherangeofvaluesofvariablesandthesetofoperationsthataredefinedforvaluesofthattype;inthecaseoffloatingpoint,typealsodeterminestheprecisionValue-thecontentsofthelocationwithwhichthevariableisassociated-Thel-valueofavariableisitsaddress-Ther-valueofavariableisitsvalueAbstractmemorycell-thephysicalcellorcollectionofcellsassociatedwithavariable11Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAttributes(continueTheConceptofBindingAbindingisanassociationbetweenanentityandanattribute,suchasbetweenavariableanditstypeorvalue,orbetweenanoperationandasymbolBindingtimeisthetimeatwhichabindingtakesplace.12Copyright©2012Addison-Wesley.Allrightsreserved.TheConceptofBindingAbinPossibleBindingTimesLanguagedesigntime--bindoperatorsymbolstooperationsLanguageimplementationtime--bindfloatingpointtypetoarepresentationCompiletime--bindavariabletoatypeinCorJavaLoadtime--bindaCorC++staticvariabletoamemorycell)Runtime--bindanonstaticlocalvariabletoamemorycell13Copyright©2012Addison-Wesley.Allrightsreserved.PossibleBindingTimesLanguageStaticandDynamicBindingAbindingisstaticifitfirstoccursbeforeruntimeandremainsunchangedthroughoutprogramexecution.Abindingisdynamicifitfirstoccursduringexecutionorcanchangeduringexecutionoftheprogram14Copyright©2012Addison-Wesley.Allrightsreserved.StaticandDynamicBindingAbiTypeBindingHowisatypespecified?Whendoesthebindingtakeplace?Ifstatic,thetypemaybespecifiedbyeitheranexplicitoranimplicitdeclaration15Copyright©2012Addison-Wesley.Allrightsreserved.TypeBindingHowisatypespecExplicit/ImplicitDeclarationAnexplicitdeclarationisaprogramstatementusedfordeclaringthetypesofvariablesAnimplicitdeclarationisadefaultmechanismforspecifyingtypesofvariablesthroughdefaultconventions,ratherthandeclarationstatementsFortran,BASIC,Perl,Ruby,JavaScript,andPHPprovideimplicitdeclarations(Fortranhasbothexplicitandimplicit)Advantage:writability(aminorconvenience)Disadvantage:reliability(lesstroublewithPerl)16Copyright©2012Addison-Wesley.Allrightsreserved.Explicit/ImplicitDeclarationAExplicit/ImplicitDeclaration(continued)Somelanguagesusetypeinferencingtodeterminetypesofvariables(context)C#-avariablecanbedeclaredwithvarandaninitialvalue.TheinitialvaluesetsthetypeVisualBASIC9.0+,ML,Haskell,F#,andGousetypeinferencing.Thecontextoftheappearanceofavariabledeterminesitstype17Copyright©2012Addison-Wesley.Allrightsreserved.Explicit/ImplicitDeclarationDynamicTypeBindingDynamicTypeBinding(JavaScript,Python,Ruby,PHP,andC#(limited))Specifiedthroughanassignmentstatemente.g.,JavaScript

list=[2,4.33,6,8]; list=17.3;Advantage:flexibility(genericprogramunits)Disadvantages:Highcost(dynamictypecheckingandinterpretation)Typeerrordetectionbythecompilerisdifficult18Copyright©2012Addison-Wesley.Allrightsreserved.DynamicTypeBindingDynamicTyVariableAttributes(continued)StorageBindings&LifetimeAllocation-gettingacellfromsomepoolofavailablecellsDeallocation-puttingacellbackintothepoolThelifetimeofavariableisthetimeduringwhichitisboundtoaparticularmemorycell19Copyright©2012Addison-Wesley.Allrightsreserved.VariableAttributes(continuedCategoriesofVariablesbyLifetimesStatic--boundtomemorycellsbeforeexecutionbeginsandremainsboundtothesamememorycellthroughoutexecution,e.g.,CandC++staticvariablesinfunctionsAdvantages:efficiency(directaddressing),history-sensitivesubprogramsupportDisadvantage:lackofflexibility(norecursion)20Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesStack-dynamic--Storagebindingsarecreatedforvariableswhentheirdeclarationstatementsareelaborated.(Adeclarationiselaboratedwhentheexecutablecodeassociatedwithitisexecuted)Ifscalar,allattributesexceptaddressarestaticallyboundlocalvariablesinCsubprograms(notdeclaredstatic)andJavamethodsAdvantage:allowsrecursion;conservesstorageDisadvantages:OverheadofallocationanddeallocationSubprogramscannotbehistorysensitiveInefficientreferences(indirectaddressing)21Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesExplicitheap-dynamic--Allocatedanddeallocatedbyexplicitdirectives,specifiedbytheprogrammer,whichtakeeffectduringexecutionReferencedonlythroughpointersorreferences,e.g.dynamicobjectsinC++(vianewanddelete),allobjectsinJavaAdvantage:providesfordynamicstoragemanagementDisadvantage:inefficientandunreliable22Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesImplicitheap-dynamic--AllocationanddeallocationcausedbyassignmentstatementsallvariablesinAPL;allstringsandarraysinPerl,JavaScript,andPHPAdvantage:flexibility(genericcode)Disadvantages:Inefficient,becauseallattributesaredynamicLossoferrordetection23Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifVariableAttributes:ScopeThescopeofavariableistherangeofstatementsoverwhichitisvisibleThelocalvariablesofaprogramunitarethosethataredeclaredinthatunitThenonlocalvariablesofaprogramunitarethosethatarevisibleintheunitbutnotdeclaredthereGlobalvariablesareaspecialcategoryofnonlocalvariablesThescoperulesofalanguagedeterminehowreferencestonamesareassociatedwithvariables24Copyright©2012Addison-Wesley.Allrightsreserved.VariableAttributes:ScopeTheStaticScope

BasedonprogramtextToconnectanamereferencetoavariable,you(orthecompiler)mustfindthedeclarationSearchprocess:searchdeclarations,firstlocally,theninincreasinglylargerenclosingscopes,untiloneisfoundforthegivennameEnclosingstaticscopes(toaspecificscope)arecalleditsstaticancestors;theneareststaticancestoriscalledastaticparentSomelanguagesallownestedsubprogramdefinitions,whichcreatenestedstaticscopes(e.g.,Ada,JavaScript,CommonLISP,Scheme,Fortran2003+,F#,andPython)25Copyright©2012Addison-Wesley.Allrightsreserved.StaticScope

BasedonprogramScope(continued)Variablescanbehiddenfromaunitbyhavinga"closer"variablewiththesamenameAdaallowsaccesstothese"hidden"variablesE.g.,26Copyright©2012Addison-Wesley.Allrightsreserved.Scope(continued)VariablescanBlocks

Amethodofcreatingstaticscopesinsideprogramunits--fromALGOL60ExampleinC:voidsub(){intcount;while(...){ intcount;count++;...}…}

-Note:legalinCandC++,butnotinJavaandC#-tooerror-prone27Copyright©2012Addison-Wesley.Allrightsreserved.Blocks

AmethodofcreatingsDeclarationOrderC99,C++,Java,andC#allowvariabledeclarationstoappearanywhereastatementcanappearInC99,C++,andJava,thescopeofalllocalvariablesisfromthedeclarationtotheendoftheblockInC#,thescopeofanyvariabledeclaredinablockisthewholeblock,regardlessofthepositionofthedeclarationintheblockHowever,avariablestillmustbedeclaredbeforeitcanbeused28Copyright©2012Addison-Wesley.Allrightsreserved.DeclarationOrderC99,C++,JavTheLETConstructMostfunctionallanguagesincludesomeformofletconstructAletconstructhastwopartsThefirstpartbindsnamestovaluesThesecondpartusesthenamesdefinedinthefirstpartInScheme: (LET( (name1expression1) … (namenexpressionn) )29Copyright©2012Addison-Wesley.Allrightsreserved.TheLETConstructMostfunctionTheLETConstruct(continued)InML: let valname1=expression1 … valnamen=expressionn in expression end;InF#:Firstpart:let

left_side=expression(left_sideiseitheranameoratuplepattern)Allthatfollowsisthesecondpart30Copyright©2012Addison-Wesley.Allrightsreserved.TheLETConstruct(continued)IDeclarationOrder(continued)InC++,Java,andC#,variablescanbedeclaredinforstatementsThescopeofsuchvariablesisrestrictedtotheforconstruct31Copyright©2012Addison-Wesley.Allrightsreserved.DeclarationOrder(continued)IGlobalScopeC,C++,PHP,andPythonsupportaprogramstructurethatconsistsofasequenceoffunctiondefinitionsinafileTheselanguagesallowvariabledeclarationstoappearoutsidefunctiondefinitionsCandC++havebothdeclarations(justattributes)anddefinitions(attributesandstorage)Adeclarationoutsideafunctiondefinitionspecifiesthatitisdefinedinanotherfile32Copyright©2012Addison-Wesley.Allrightsreserved.GlobalScopeC,C++,PHP,andPGlobalScope(continued)PHPProgramsareembeddedinHTMLmarkupdocuments,inanynumberoffragments,somestatementsandsomefunctiondefinitionsThescopeofavariable(implicitly)declaredinafunctionislocaltothefunctionThescopeofavariableimplicitlydeclaredoutsidefunctionsisfromthedeclarationtotheendoftheprogram,butskipsoveranyinterveningfunctionsGlobalvariablescanbeaccessedinafunctionthroughthe$GLOBALSarrayorbydeclaringitglobal33Copyright©2012Addison-Wesley.Allrightsreserved.GlobalScope(continued)PHP33GlobalScope(continued)PythonAglobalvariablecanbereferencedinfunctions,butcanbeassignedinafunctiononlyifithasbeendeclaredtobeglobalinthefunction34Copyright©2012Addison-Wesley.Allrightsreserved.GlobalScope(continued)PythonEvaluationofStaticScoping

WorkswellinmanysituationsProblems:Inmostcases,toomuchaccessispossibleAsaprogramevolves,theinitialstructureisdestroyedandlocalvariablesoftenbecomeglobal;subprogramsalsogravitatetowardbecomeglobal,ratherthannested35Copyright©2012Addison-Wesley.Allrightsreserved.EvaluationofStaticScoping

WDynamicScope

Basedoncallingsequencesofprogramunits,nottheirtextuallayout(temporalversusspatial)Referencestovariablesareconnectedtodeclarationsbysearchingbackthroughthechainofsubprogramcallsthatforcedexecutiontothispoint36Copyright©2012Addison-Wesley.Allrightsreserved.DynamicScope

BasedoncallingScopeExamplefunctionbig(){

functionsub1()

varx=7;

functionsub2(){

vary=x;}

varx=3;}StaticscopingReferencetoxinsub2istobig'sxDynamicscopingReferencetoxinsub2istosub1'sx

bigcallssub1sub1callssub2sub2usesx37Copyright©2012Addison-Wesley.Allrightsreserved.ScopeExampleScopeExampleEvaluationofDynamicScoping:Advantage:convenienceDisadvantages:

Whileasubprogramisexecuting,itsvariablesarevisibletoallsubprogramsitcallsImpossibletostaticallytypecheck3.Poorreadability-itisnotpossibletostaticallydeterminethetypeofavariable38Copyright©2012Addison-Wesley.Allrightsreserved.ScopeExample38Copyright©201ScopeandLifetimeScopeandlifetimearesometimescloselyrelated,butaredifferentconceptsConsiderastaticvariableinaCorC++function39Copyright©2012Addison-Wesley.Allrightsreserved.ScopeandLifetimeScopeandliReferencingEnvironmentsThereferencingenvironmentofastatementisthecollectionofallnamesthatarevisibleinthestatementInastatic-scopedlanguage,itisthelocalvariablesplusallofthevisiblevariablesinalloftheenclosingscopesAsubprogramisactiveifitsexecutionhasbegunbuthasnotyetterminatedInadynamic-scopedlanguage,thereferencingenvironmentisthelocalvariablesplusallvisiblevariablesinallactivesubprograms40Copyright©2012Addison-Wesley.Allrightsreserved.ReferencingEnvironmentsThereNamedConstantsAnamedconstantisavariablethatisboundtoavalueonlywhenitisboundtostorageAdvantages:readabilityandmodifiabilityUsedtoparameterizeprogramsThebindingofvaluestonamedconstantscanbeeitherstatic(calledmanifestconstants)ordynamicLanguages:Ada,C++,andJava:expressionsofanykind,dynamicallyboundC#hastwokinds,readonlyandconst-thevaluesofconstnamedconstantsareboundatcompiletime-Thevaluesofreadonlynamedconstantsaredynamicallybound41Copyright©2012Addison-Wesley.Allrightsreserved.NamedConstantsAnamedconstan经常不断地学习,你就什么都知道。你知道得越多,你就越有力量StudyConstantly,AndYouWillKnowEverything.TheMoreYouKnow,TheMorePowerfulYouWillBe写在最后经常不断地学习,你就什么都知道。你知道得越多,你就越有力量写42谢谢你的到来学习并没有结束,希望大家继续努力LearningIsNotOver.IHopeYouWillContinueToWorkHard演讲人:XXXXXX时间:XX年XX月XX日

谢谢你的到来演讲人:XXXXXX43Chapter5Names,Bindings,andScopesChapter5Names,Bindings,andChapter5TopicsIntroductionNamesVariablesTheConceptofBindingScopeScopeandLifetimeReferencingEnvironmentsNamedConstants45Copyright©2012Addison-Wesley.Allrightsreserved.Chapter5TopicsIntroduction2IntroductionImperativelanguagesareabstractionsofvonNeumannarchitectureMemoryProcessorVariablesarecharacterizedbyattributesTodesignatype,mustconsiderscope,lifetime,typechecking,initialization,andtypecompatibility46Copyright©2012Addison-Wesley.Allrightsreserved.IntroductionImperativelanguagNamesDesignissuesfornames:Arenamescasesensitive?Arespecialwordsreservedwordsorkeywords?47Copyright©2012Addison-Wesley.Allrightsreserved.NamesDesignissuesfornames:4Names(continued)LengthIftooshort,theycannotbeconnotativeLanguageexamples:FORTRAN95:maximumof31C99:nolimitbutonlythefirst63aresignificant;also,externalnamesarelimitedtoamaximumof31C#,Ada,andJava:nolimit,andallaresignificantC++:nolimit,butimplementersoftenimposeone48Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)Length5CopyriNames(continued)SpecialcharactersPHP:allvariablenamesmustbeginwithdollarsignsPerl:allvariablenamesbeginwithspecialcharacters,whichspecifythevariable’stypeRuby:variablenamesthatbeginwith@areinstancevariables;thosethatbeginwith@@areclassvariables49Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)SpecialcharaNames(continued)CasesensitivityDisadvantage:readability(namesthatlookalikearedifferent)NamesintheC-basedlanguagesarecasesensitiveNamesinothersarenotWorseinC++,Java,andC#becausepredefinednamesaremixedcase(e.g.IndexOutOfBoundsException)50Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)CasesensitivNames(continued)SpecialwordsAnaidtoreadability;usedtodelimitorseparatestatementclausesAkeywordisawordthatisspecialonlyincertaincontexts,e.g.,inFortranRealVarName

(Realisadatatypefollowedwithaname,thereforeRealisakeyword)Real=3.4

(Realisavariable) Areservedwordisaspecialwordthatcannotbeusedasauser-definednamePotentialproblemwithreservedwords:Iftherearetoomany,manycollisionsoccur(e.g.,COBOLhas300reservedwords!)51Copyright©2012Addison-Wesley.Allrightsreserved.Names(continued)SpecialwordsVariablesAvariableisanabstractionofamemorycellVariablescanbecharacterizedasasextupleofattributes:NameAddressValueTypeLifetimeScope52Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAvariableisanabstVariablesAttributesName-notallvariableshavethemAddress-thememoryaddresswithwhichitisassociatedAvariablemayhavedifferentaddressesatdifferenttimesduringexecutionAvariablemayhavedifferentaddressesatdifferentplacesinaprogramIftwovariablenamescanbeusedtoaccessthesamememorylocation,theyarecalledaliasesAliasesarecreatedviapointers,referencevariables,CandC++unionsAliasesareharmfultoreadability(programreadersmustrememberallofthem)53Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAttributesName-notVariablesAttributes(continued)Type-determinestherangeofvaluesofvariablesandthesetofoperationsthataredefinedforvaluesofthattype;inthecaseoffloatingpoint,typealsodeterminestheprecisionValue-thecontentsofthelocationwithwhichthevariableisassociated-Thel-valueofavariableisitsaddress-Ther-valueofavariableisitsvalueAbstractmemorycell-thephysicalcellorcollectionofcellsassociatedwithavariable54Copyright©2012Addison-Wesley.Allrightsreserved.VariablesAttributes(continueTheConceptofBindingAbindingisanassociationbetweenanentityandanattribute,suchasbetweenavariableanditstypeorvalue,orbetweenanoperationandasymbolBindingtimeisthetimeatwhichabindingtakesplace.55Copyright©2012Addison-Wesley.Allrightsreserved.TheConceptofBindingAbinPossibleBindingTimesLanguagedesigntime--bindoperatorsymbolstooperationsLanguageimplementationtime--bindfloatingpointtypetoarepresentationCompiletime--bindavariabletoatypeinCorJavaLoadtime--bindaCorC++staticvariabletoamemorycell)Runtime--bindanonstaticlocalvariabletoamemorycell56Copyright©2012Addison-Wesley.Allrightsreserved.PossibleBindingTimesLanguageStaticandDynamicBindingAbindingisstaticifitfirstoccursbeforeruntimeandremainsunchangedthroughoutprogramexecution.Abindingisdynamicifitfirstoccursduringexecutionorcanchangeduringexecutionoftheprogram57Copyright©2012Addison-Wesley.Allrightsreserved.StaticandDynamicBindingAbiTypeBindingHowisatypespecified?Whendoesthebindingtakeplace?Ifstatic,thetypemaybespecifiedbyeitheranexplicitoranimplicitdeclaration58Copyright©2012Addison-Wesley.Allrightsreserved.TypeBindingHowisatypespecExplicit/ImplicitDeclarationAnexplicitdeclarationisaprogramstatementusedfordeclaringthetypesofvariablesAnimplicitdeclarationisadefaultmechanismforspecifyingtypesofvariablesthroughdefaultconventions,ratherthandeclarationstatementsFortran,BASIC,Perl,Ruby,JavaScript,andPHPprovideimplicitdeclarations(Fortranhasbothexplicitandimplicit)Advantage:writability(aminorconvenience)Disadvantage:reliability(lesstroublewithPerl)59Copyright©2012Addison-Wesley.Allrightsreserved.Explicit/ImplicitDeclarationAExplicit/ImplicitDeclaration(continued)Somelanguagesusetypeinferencingtodeterminetypesofvariables(context)C#-avariablecanbedeclaredwithvarandaninitialvalue.TheinitialvaluesetsthetypeVisualBASIC9.0+,ML,Haskell,F#,andGousetypeinferencing.Thecontextoftheappearanceofavariabledeterminesitstype60Copyright©2012Addison-Wesley.Allrightsreserved.Explicit/ImplicitDeclarationDynamicTypeBindingDynamicTypeBinding(JavaScript,Python,Ruby,PHP,andC#(limited))Specifiedthroughanassignmentstatemente.g.,JavaScript

list=[2,4.33,6,8]; list=17.3;Advantage:flexibility(genericprogramunits)Disadvantages:Highcost(dynamictypecheckingandinterpretation)Typeerrordetectionbythecompilerisdifficult61Copyright©2012Addison-Wesley.Allrightsreserved.DynamicTypeBindingDynamicTyVariableAttributes(continued)StorageBindings&LifetimeAllocation-gettingacellfromsomepoolofavailablecellsDeallocation-puttingacellbackintothepoolThelifetimeofavariableisthetimeduringwhichitisboundtoaparticularmemorycell62Copyright©2012Addison-Wesley.Allrightsreserved.VariableAttributes(continuedCategoriesofVariablesbyLifetimesStatic--boundtomemorycellsbeforeexecutionbeginsandremainsboundtothesamememorycellthroughoutexecution,e.g.,CandC++staticvariablesinfunctionsAdvantages:efficiency(directaddressing),history-sensitivesubprogramsupportDisadvantage:lackofflexibility(norecursion)63Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesStack-dynamic--Storagebindingsarecreatedforvariableswhentheirdeclarationstatementsareelaborated.(Adeclarationiselaboratedwhentheexecutablecodeassociatedwithitisexecuted)Ifscalar,allattributesexceptaddressarestaticallyboundlocalvariablesinCsubprograms(notdeclaredstatic)andJavamethodsAdvantage:allowsrecursion;conservesstorageDisadvantages:OverheadofallocationanddeallocationSubprogramscannotbehistorysensitiveInefficientreferences(indirectaddressing)64Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesExplicitheap-dynamic--Allocatedanddeallocatedbyexplicitdirectives,specifiedbytheprogrammer,whichtakeeffectduringexecutionReferencedonlythroughpointersorreferences,e.g.dynamicobjectsinC++(vianewanddelete),allobjectsinJavaAdvantage:providesfordynamicstoragemanagementDisadvantage:inefficientandunreliable65Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifCategoriesofVariablesbyLifetimesImplicitheap-dynamic--AllocationanddeallocationcausedbyassignmentstatementsallvariablesinAPL;allstringsandarraysinPerl,JavaScript,andPHPAdvantage:flexibility(genericcode)Disadvantages:Inefficient,becauseallattributesaredynamicLossoferrordetection66Copyright©2012Addison-Wesley.Allrightsreserved.CategoriesofVariablesbyLifVariableAttributes:ScopeThescopeofavariableistherangeofstatementsoverwhichitisvisibleThelocalvariablesofaprogramunitarethosethataredeclaredinthatunitThenonlocalvariablesofaprogramunitarethosethatarevisibleintheunitbutnotdeclaredthereGlobalvariablesareaspecialcategoryofnonlocalvariablesThescoperulesofalanguagedeterminehowreferencestonamesareassociatedwithvariables67Copyright©2012Addison-Wesley.Allrightsreserved.VariableAttributes:ScopeTheStaticScope

Basedonp

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论