You are on page 1of 24

1/10/2017

Scope(computerscience)Wikipedia

Scope(computerscience)
FromWikipedia,thefreeencyclopedia

Incomputerprogramming,thescopeofanamebindinganassociationofanametoanentity,
suchasavariableisthepartofacomputerprogramwherethebindingisvalid:wherethe
namecanbeusedtorefertotheentity.Inotherpartsoftheprogramthenamemayrefertoa
differententity(itmayhaveadifferentbinding),ortonothingatall(itmaybeunbound).The
scopeofabindingisalsoknownasthevisibilityofanentity,particularlyinolderormore
technicalliteraturethisisfromtheperspectiveofthereferencedentity,notthereferencing
name.Ascopeisapartofaprogramthatisorcanbethescopeforasetofbindingsaprecise
definitionistricky,butincasualuseandinpracticelargelycorrespondstoablock,afunction,or
afile,dependingonlanguageandtypeofentity.Theterm"scope"isalsousedtorefertotheset
ofallentitiesthatarevisibleornamesthatarevalidwithinaportionoftheprogramoratagiven
pointinaprogram,whichismorecorrectlyreferredtoascontextorenvironment.[a]
Strictlyspeaking[b]andinpracticeformostprogramminglanguages,"partofaprogram"refers
to"portionofthesourcecode(areaoftext)",andisknownaslexicalscope.Insomelanguages,
however,"partofaprogram"refersto"portionofruntime(timeperiodduringexecution)",and
isknownasdynamicscope.Bothofthesetermsaresomewhatmisleadingtheymisuse
technicalterms,asdiscussedinthedefinitionbutthedistinctionitselfisaccurateandprecise,
andthesearethestandardrespectiveterms.Lexicalscopeisthemainfocusofthisarticle,with
dynamicscopeunderstoodbycontrastwithlexicalscope.
Inmostcases,nameresolutionbasedonlexicalscopeisstraightforwardtouseandto
implement,asinuseonecansimplyreadbackwardsinthesourcecodetodeterminetowhich
entityanamerefers,andinimplementationonecansimplymaintainalistofnamesandcontexts
whencompilingorinterpretingaprogram.Basicdifficultiesariseinnamemasking,forward
declarations,andhoisting,whileconsiderablysubtleronesarisewithnonlocalvariables,
particularlyinclosures.

Contents
1 Definition
1.1 Lexicalscopevs.dynamicscope
1.2 Relatedconcepts
2 Use
3 Overview
4 Levelsofscope
4.1 Expressionscope
4.2 Blockscope
4.3 Functionscope
4.4 Filescope
4.5 Modulescope

https://en.wikipedia.org/wiki/Scope_(computer_science)

1/24

1/10/2017

Scope(computerscience)Wikipedia

4.6 Globalscope
5 Lexicalscopingvs.dynamicscoping
6 Lexicalscoping
6.1 History
7 Dynamicscoping
7.1 Macroexpansion
8 Qualifiedidentifiers
9 Bylanguage
9.1 C
9.2 C++
9.3 Go
9.4 Java
9.5 JavaScript
9.6 Lisp
9.7 Python
9.8 R
10 Seealso
11 Notes
12 References

Definition
Thestrictdefinitionofthe(lexical)"scope"ofaname(identifier)isunambiguousitis"the
portionofsourcecodeinwhichabindingofanamewithanentityapplies"andisvirtually
unchangedfromits1960definitioninthespecificationofALGOL60.Representativelanguage
specificationfollow.
ALGOL60(1960)[1]
Thefollowingkindsofquantitiesaredistinguished:simplevariables,arrays,labels,
switches,andprocedures.Thescopeofaquantityisthesetofstatementsandexpressions
inwhichthedeclarationoftheidentifierassociatedwiththatquantityisvalid.
C(2007)[2]
Anidentifiercandenoteanobjectafunctionatagoramemberofastructure,union,or
enumerationatypedefnamealabelnameamacronameoramacroparameter.The
sameidentifiercandenotedifferententitiesatdifferentpointsintheprogram.[...]For
eachdifferententitythatanidentifierdesignates,theidentifierisvisible(i.e.,canbeused)
onlywithinaregionofprogramtextcalleditsscope.
Go(2013)[3]
Adeclarationbindsanonblankidentifiertoaconstant,type,variable,function,label,or
package.[...]Thescopeofadeclaredidentifieristheextentofsourcetextinwhichthe
identifierdenotesthespecifiedconstant,type,variable,function,label,orpackage.
Mostcommonly"scope"referstowhenagivennamecanrefertoagivenvariablewhena
declarationhaseffectbutcanalsoapplytootherentities,suchasfunctions,types,classes,
labels,constants,andenumerations.

https://en.wikipedia.org/wiki/Scope_(computer_science)

2/24

1/10/2017

Scope(computerscience)Wikipedia

Lexicalscopevs.dynamicscope
Afundamentaldistinctioninscopingiswhat"partofaprogram"means.Inlanguageswith
lexicalscope(alsocalledstaticscope),nameresolutiondependsonthelocationinthesource
codeandthelexicalcontext,whichisdefinedbywherethenamedvariableorfunctionis
defined.Incontrast,inlanguageswithdynamicscopethenameresolutiondependsuponthe
programstatewhenthenameisencounteredwhichisdeterminedbytheexecutioncontextor
callingcontext.Inpractice,withlexicalscopeavariable'sdefinitionisresolvedbysearchingits
containingblockorfunction,thenifthatfailssearchingtheoutercontainingblock,andsoon,
whereaswithdynamicscopethecallingfunctionissearched,thenthefunctionwhichcalledthat
callingfunction,andsoon,progressingupthecallstack.[4]Ofcourse,inbothrules,wefirstlook
foralocaldefinitionofavariable.
Mostmodernlanguagesuselexicalscopingforvariablesandfunctions,thoughdynamicscoping
isusedinsomelanguages,notablysomedialectsofLisp,some"scripting"languageslikePerl,
andsometemplatelanguages.[c]Eveninlexicallyscopedlanguages,scopeforclosurescanbe
confusingtotheuninitiated,asthesedependonthelexicalcontextwheretheclosureisdefined,
notwhereitiscalled.
Lexicalresolutioncanbedeterminedatcompiletime,andisalsoknownasearlybinding,while
dynamicresolutioncaningeneralonlybedeterminedatruntime,andthusisknownaslate
binding.

Relatedconcepts
Inobjectorientedprogramming,dynamicdispatchselectsanobjectmethodatruntime,though
whethertheactualnamebindingisdoneatcompiletimeorruntimedependsonthelanguage.
Defactodynamicscopingiscommoninmacrolanguages,whichdonotdirectlydoname
resolution,butinsteadexpandinplace.
SomeprogrammingframeworkslikeAngularJSusetheterm"scope"tomeansomethingentirely
differentthanhowitisusedinthisarticle.Inthoseframeworksthescopeisjustanobjectofthe
programminglanguagethattheyuse(JavaScriptincaseofAngularJS)thatisusedincertain
waysbytheframeworktoemulatedynamicscopeinalanguagethatuseslexicalscopeforits
variables.ThoseAngularJSscopescanthemselvesbeinscopeoroutofscope(usingtheusual
meaningoftheterm)inanygivenpartoftheprogram,followingtheusualrulesofvariable
scopeofthelanguagelikeanyotherobject,andusingtheirowninheritanceandtransclusion
rules.InthecontextofAngularJS,sometimestheterm"$scope"(withadollarsign)isusedto
avoidconfusion,butusingthedollarsigninvariablenamesisoftendiscouragedbythestyle
guides.[5]

Use

https://en.wikipedia.org/wiki/Scope_(computer_science)

3/24

1/10/2017

Scope(computerscience)Wikipedia

Scopeisanimportantcomponentofnameresolution,[d]whichisinturnfundamentaltolanguage
semantics.Nameresolution(includingscope)variesbetweenprogramminglanguages,and
withinaprogramminglanguage,variesbytypeofentitytherulesforscopearecalledscope
rulesorscopingrules.Togetherwithnamespaces,scopingrulesarecrucialinmodular
programming,soachangeinonepartoftheprogramdoesnotbreakanunrelatedpart.

Overview
Whendiscussingscope,therearethreebasicconcepts:scope,extent,andcontext."Scope"and
"context"inparticulararefrequentlyconfused:scopeisapropertyofanidentifier,andisfixed,
whilecontextisapropertyofaprogram,whichvariesbyposition.Moreprecisely,contextisa
propertyofapositionintheprogram,eitherapositioninthesourcecode(lexicalcontext)ora
pointduringruntime(executioncontext,runtimecontext,orcallingcontext).Executioncontext
consistsoflexicalcontext(atthecurrentexecutionpoint)plusadditionalruntimestatesuchas
thecallstack.[e]Thus,whentheexecutionpointofaprogramisinavariablename'sscope,the
"variable(name)isincontext"(meaning"inthecontextatthispoint"),andwhentheexecution
point"exitsavariable(name)'sscope",suchasbyreturningfromafunction,"thevariable
(name)goesoutofcontext".[f]Narrowlyspeaking,duringexecutionaprogramentersandexits
variousscopes,andatapointinexecutionidentifiersare"incontext"or"notincontext",hence
identifiers"comeintocontext"or"gooutofcontext"astheprogramentersorexitsthescope
howeverinpracticeusageismuchlooser.
Scopeisasourcecodelevelconcept,andapropertyofidentifiers,particularlyvariableor
functionnamesidentifiersinthesourcecodearereferencestoentitiesintheprogramandis
partofthebehaviorofacompilerorinterpreterofalanguage.Assuch,issuesofscopeare
similartopointers,whichareatypeofreferenceusedinprogramsmoregenerally.Usingthe
valueofavariablewhenthenameisincontextbutthevariableisuninitializedisanalogousto
dereferencing(accessingthevalueof)awildpointer,asitisundefined.However,asvariables
arenotdestroyeduntiltheygooutofcontext,theanalogofadanglingpointerdoesnotexist.
Forentitiessuchasvariables,scopeisasubsetoflifetime(alsoknownasextent)anamecan
onlyrefertoavariablethatexists(possiblywithundefinedvalue),butvariablesthatexistarenot
necessarilyvisible:avariablemayexistbutbeinaccessible(thevalueisstoredbutnotreferred
towithinagivencontext),oraccessiblebutnotviathegivenname,inwhichcaseitisoutof
context(theprogramis"outofthescopeofthename").Inothercases"lifetime"isirrelevanta
label(namedpositioninthesourcecode)haslifetimeidenticalwiththeprogram(forstatically
compiledlanguages),butmaybeinoroutofcontextatagivenpointintheprogram,and
likewiseforstaticvariablesastaticglobalvariableisincontextfortheentireprogram,whilea
staticlocalvariableisonlyincontextwithinafunctionorotherlocalcontext,butbothhave
lifetimeoftheentirerunoftheprogram.
Determiningwhichentityanidentifierreferstoisknownasnameresolutionornamebinding
(particularlyinobjectorientedprogramming),andvariesbetweenlanguages.Givenan
identifier,thelanguage(properly,thecompilerorinterpreter)checksallentitiesthatarein

https://en.wikipedia.org/wiki/Scope_(computer_science)

4/24

1/10/2017

Scope(computerscience)Wikipedia

contextformatchesincaseofambiguity(twoentitieswiththesamename,suchasaglobaland
localvariablewiththesamename),thenameresolutionrulesareusedtodistinguishthem.Most
frequently,nameresolutionreliesonan"innertoouter"rule,suchasthePythonLEGB(Local,
Enclosing,Global,Builtin)rule:namesimplicitlyresolvestothenarrowestrelevantcontext.In
somecasesnameresolutioncanbeexplicitlyspecified,suchasbytheglobalandnonlocal
keywordsinPythoninothercasesthedefaultrulescannotbeoverridden.
Whentwoidenticalidentifiersareincontextatthesametime,referringtodifferententities,one
saysthatnamemaskingisoccurring,wherethehigherpriorityname(usuallyinnermost)is
"masking"thelowerpriorityname.Atthelevelofvariables,thisisknownasvariable
shadowing.Duetothepotentialforlogicerrorsfrommasking,somelanguagesdisallowor
discouragemasking,raisinganerrororwarningatcompiletimeorruntime.
Variousprogramminglanguageshavevariousdifferentscopingrulesfordifferentkindsof
declarationsandidentifiers.Suchscopingruleshavealargeeffectonlanguagesemanticsand,
consequently,onthebehaviorandcorrectnessofprograms.InlanguageslikeC++,accessingan
unboundvariabledoesnothavewelldefinedsemanticsandmayresultinundefinedbehavior,
similartoreferringtoadanglingpointeranddeclarationsoridentifiersusedoutsidetheirscope
willgeneratesyntaxerrors.
Scopesarefrequentlytiedtootherlanguageconstructsanddeterminedimplicitly,butmany
languagesalsoofferconstructsspecificallyforcontrollingscope.

Levelsofscope
Scopecanvaryfromaslittleasasingleexpressiontoasmuchastheentireprogram,withmany
possiblegradationsinbetween.Thesimplestscopingruleisglobalscopeallentitiesarevisible
throughouttheentireprogram.Themostbasicmodularscopingruleistwolevelscoping,witha
globalscopeanywhereintheprogram,andlocalscopewithinafunction.Moresophisticated
modularprogrammingallowsaseparatemodulescope,wherenamesarevisiblewithinthe
module(privatetothemodule)butnotvisibleoutsideit.Withinafunction,somelanguages,
suchasC,allowblockscopetorestrictscopetoasubsetofafunctionothers,notablyfunctional
languages,allowexpressionscope,torestrictscopetoasingleexpression.Otherscopesinclude
filescope(notablyinC),whichfunctionssimilarlytomodulescope,andblockscopeoutsideof
functions(notablyinPerl).
Asubtleissueisexactlywhenascopebeginsandends.Insomelanguages,suchasinC,ascope
startsatdeclaration,andthusdifferentnamesdeclaredwithinagivenblockcanhavedifferent
scopes.Thisrequiresdeclaringfunctionsbeforeuse,thoughnotnecessarilydefiningthem,and
requiresforwarddeclarationinsomecases,notablyformutualrecursion.Inotherlanguages,
suchasJavaScriptorPython,aname'sscopebeginsatthestartoftherelevantblock(suchasthe
startofafunction),regardlessofwhereitisdefined,andallnameswithinagivenblockhavethe
samescopeinJavaScriptthisisknownasvariablehoisting.However,whenthenameisbound
toavaluevaries,andbehaviorofincontextnamesthathaveundefinedvaluediffers:inPython

https://en.wikipedia.org/wiki/Scope_(computer_science)

5/24

1/10/2017

Scope(computerscience)Wikipedia

useofundefinedvariablesyieldsaruntimeerror,whileinJavaScriptundefinedvariablesare
usable(withundefinedvalue),butfunctiondeclarationsarealsohoistedtothetopofthe
containingfunctionandusablethroughoutthefunction.

Expressionscope
Manylanguages,especiallyfunctionallanguages,offerafeaturecalledletexpressions,which
allowadeclaration'sscopetobeasingleexpression.Thisisconvenientif,forexample,an
intermediatevalueisneededforacomputation.Forexample,inStandardML,iff()returns12,
thenletvalx=f()inx*xendisanexpressionthatevaluatesto144,usingatemporary
variablenamedxtoavoidcallingf()twice.Somelanguageswithblockscopeapproximatethis
functionalitybyofferingsyntaxforablocktobeembeddedintoanexpressionforexample,the
aforementionedStandardMLexpressioncouldbewritteninPerlasdo{my$x=f();$x*$x
},orinGNUCas({intx=f();x*x;}).
InPython,auxiliaryvariablesingeneratorexpressionsandlistcomprehensions(inPython3)
haveexpressionscope.
InC,variablenamesinafunctionprototypehaveexpressionscope,knowninthiscontextas
functionprotocolscope.Asthevariablenamesintheprototypearenotreferredto(theymaybe
differentintheactualdefinition)theyarejustdummiestheseareoftenomitted,thoughthey
maybeusedforgeneratingdocumentation,forinstance.

Blockscope
Many,butnotall,blockstructuredprogramminglanguagesallowscopetoberestrictedtoa
block,whichisknownasblockscope.ThisbeganwithALGOL60,where"[e]verydeclaration
...isvalidonlyforthatblock.",[6]andtodayisparticularlyassociatedwithlanguagesinthe
PascalandCfamiliesandtraditions.Mostoftenthisblockiscontainedwithinafunction,thus
restrictingthescopetoapartofafunction,butinsomecases,suchasPerl,theblockmaynotbe
withinafunction.
Arepresentativeexampleoftheuseofblock
unsignedintsum_of_squares(constunsignedintN){
scopeistheCcodeshownhere,wheretwo
unsignedintret=0;
variablesarescopedtotheloop:theloop
for(unsignedintn=1;n<=N;n++){
variablen,whichisinitializedonceand
constunsignedintn_squared=n*n;
ret+=n_squared;
incrementedoneachiterationoftheloop,and
}
theauxiliaryvariablen_squared,whichis
returnret;
}
initializedateachiteration.Thepurposeisto
avoidaddingvariablestothefunctionscope
thatareonlyrelevanttoaparticularblockforexample,thispreventserrorswherethegeneric
loopvariableihasaccidentallyalreadybeensettoanothervalue.Inthisexampletheexpression
n*nwouldgenerallynotbeassignedtoanauxiliaryvariable,andthebodyoftheloopwould
simplybewrittenret+=n*nbutinmorecomplicatedexamplesauxiliaryvariablesareuseful.

https://en.wikipedia.org/wiki/Scope_(computer_science)

6/24

1/10/2017

Scope(computerscience)Wikipedia

Blocksareprimarilyusedforcontrolflow,suchaswithif,while,andforloops,andinthese
casesblockscopemeansthescopeofvariabledependsonthestructureofafunction'sflowof
execution.However,languageswithblockscopetypicallyalsoallowtheuseof"naked"blocks,
whosesolepurposeistoallowfinegrainedcontrolofvariablescope.Forexample,anauxiliary
variablemaybedefinedinablock,thenused(say,addedtoavariablewithfunctionscope)and
discardedwhentheblockends,orawhileloopmightbeenclosedinablockthatinitializes
variablesusedinsidetheloopthatshouldonlybeinitializedonce.
Asubtletyofseveralprogramminglanguages,suchasAlgol68andC(demonstratedinthis
exampleandstandardizedsinceC99),isthatblockscopevariablescanbedeclarednotonly
withinthebodyoftheblock,butalsowithinthecontrolstatement,ifany.Thisisanalogousto
functionparameters,whicharedeclaredinthefunctiondeclaration(beforetheblockofthe
functionbodystarts),andinscopeforthewholefunctionbody.Thisisprimarilyusedinfor
loops,whichhaveaninitializationstatementseparatefromtheloopcondition,unlikewhile
loops,andisacommonidiom.
Blockscopecanbeusedforshadowing.Inthisexample,insidetheblocktheauxiliaryvariable
couldalsohavebeencalledn,shadowingtheparametername,butthisisconsideredpoorstyle
duetothepotentialforerrors.Furthermore,somedescendantsofC,suchasJavaandC#,despite
havingsupportforblockscope(inthatalocalvariablecanbemadetogooutofscopebeforethe
endofafunction),donotallowonelocalvariabletohideanother.Insuchlanguages,the
attempteddeclarationofthesecondnwouldresultinasyntaxerror,andoneofthenvariables
wouldhavetoberenamed.
Ifablockisusedtosetthevalueofavariable,blockscoperequiresthatthevariablebedeclared
outsideoftheblock.Thiscomplicatestheuseofconditionalstatementswithsingleassignment.
Forexample,inPython,whichdoesnotuseblockscope,onemayinitializeavariableassuch:
ifc:
a='foo'
else:
a=''

whereaisaccessibleaftertheifstatement.
InPerl,whichhasblockscope,thisinsteadrequiresdeclaringthevariablepriortotheblock:
my$a;
if(c){
$a='foo';
}else{
$a='';
}

Oftenthisisinsteadrewrittenusingmultipleassignment,initializingthevariabletoadefault
value.InPython(whereitisnotnecessary)thiswouldbe:

https://en.wikipedia.org/wiki/Scope_(computer_science)

7/24

1/10/2017

Scope(computerscience)Wikipedia

a=''
ifc:
a='foo'

whileinPerlthiswouldbe:
my$a='';
if(c){
$a='foo';
}

Incaseofasinglevariableassignment,analternativeistousetheternaryoperatortoavoida
block,butthisisnotingeneralpossibleformultiplevariableassignments,andisdifficulttoread
forcomplexlogic.
ThisisamoresignificantissueinC,notablyforstringassignment,asstringinitializationcan
automaticallyallocatememory,whilestringassignmenttoanalreadyinitializedvariablerequires
allocatingmemory,astringcopy,andcheckingthatthesearesuccessful.
Somelanguagesallowtheconceptofblockscopetobeapplied,to
{my$counter=0;
varyingextents,outsideofafunction.Forexample,inthePerl
subincrement_counter()
snippetatright,$counterisavariablenamewithblockscope(due
{$counter=$counter+1;
totheuseofthemykeyword),whileincrement_counterisafunction return$counter;
}
namewithglobalscope.Eachcalltoincrement_counterwill
}
increasethevalueof$counterbyone,andreturnthenewvalue.
Codeoutsideofthisblockcancallincrement_counter,butcannot
otherwiseobtainoralterthevalueof$counter.ThisidiomallowsonetodefineclosuresinPerl.

Functionscope
Mostofthecommonlyusedprogramminglanguagesofferawaytocreatealocalvariableina
functionorsubroutine:avariablewhosescopeends(thatgoesoutofcontext)whenthefunction
returns.Inmostcasesthelifetimeofthevariableisthedurationofthefunctioncallitisan
automaticvariable,createdwhenthefunctionstarts(orthevariableisdeclared),destroyedwhen
thefunctionreturnswhilethescopeofthevariableiswithinthefunction,thoughthemeaning
of"within"dependsonwhetherscopingislexicalordynamic.However,somelanguages,such
asC,alsoprovideforstaticlocalvariables,wherethelifetimeofthevariableistheentire
lifetimeoftheprogram,butthevariableisonlyincontextwheninsidethefunction.Inthecase
ofstaticlocalvariables,thevariableiscreatedwhentheprograminitializes,anddestroyedonly
whentheprogramterminates,aswithastaticglobalvariable,butisonlyincontextwithina
function,likeanautomaticlocalvariable.
Importantly,inlexicalscopingavariablewithfunctionscopehasscopeonlywithinthelexical
contextofthefunction:itmovesoutofcontextwhenanotherfunctioniscalledwithinthe
function,andmovesbackintocontextwhenthefunctionreturnscalledfunctionshaveno

https://en.wikipedia.org/wiki/Scope_(computer_science)

8/24

1/10/2017

Scope(computerscience)Wikipedia

accesstothelocalvariablesofcallingfunctions,andlocalvariablesareonlyincontextwithin
thebodyofthefunctioninwhichtheyaredeclared.Bycontrast,indynamicscoping,thescope
extendstotheruntimecontextofthefunction:localvariablesstayincontextwhenanother
functioniscalled,onlymovingoutofcontextwhenthedefiningfunctionends,andthuslocal
variablesareincontextofthefunctioninwhichtheyaredefinedandallcalledfunctions.In
languageswithlexicalscopingandnestedfunctions,localvariablesareincontextfornested
functions,sincethesearewithinthesamelexicalcontext,butnotforotherfunctionsthatarenot
lexicallynested.Alocalvariableofanenclosingfunctionisknownasanonlocalvariablefor
thenestedfunction.Functionscopeisalsoapplicabletoanonymousfunctions.
Forexample,inthesnippetofPythoncodeontheright,twofunctionsare
defined:squareandsum_of_squares.squarecomputesthesquareofa
numbersum_of_squarescomputesthesumofallsquaresuptoanumber.
(Forexample,square(4)is42=16,andsum_of_squares(4)is
02+12+22+32+42=30.)

defsquare(n):
returnn*n

defsum_of_squares(n):
total=0
i=0
whilei<=n:
total+=square(i)
i+=1
returntotal

Eachofthesefunctionshasavariablenamednthatrepresentsthe
argumenttothefunction.Thesetwonvariablesarecompletelyseparate
andunrelated,despitehavingthesamename,becausetheyarelexically
scopedlocalvariables,withfunctionscope:eachone'sscopeisitsown,lexicallyseparate,
function,sotheydon'toverlap.Therefore,sum_of_squarescancallsquarewithoutitsownn
beingaltered.Similarly,sum_of_squareshasvariablesnamedtotalandithesevariables,because
oftheirlimitedscope,willnotinterferewithanyvariablesnamedtotalorithatmightbelongto
anyotherfunction.Inotherwords,thereisnoriskofanamecollisionbetweentheseidentifiers
andanyunrelatedidentifiers,eveniftheyareidentical.
Notealsothatnonamemaskingisoccurring:onlyonevariablenamednisincontextatany
giventime,asthescopesdonotoverlap.Bycontrast,wereasimilarfragmenttobewrittenina
languagewithdynamicscope,theninthecallingfunctionwouldremainincontextinthecalled
functionthescopeswouldoverlapandwouldbemasked("shadowed")bythenewninthe
calledfunction.

Functionscopeissignificantlymorecomplicatediffunctionsarefirstclassobjectsandcanbe
createdlocallytoafunctionandthenreturned.Inthiscaseanyvariablesinthenestedfunction
thatarenotlocaltoit(unboundvariablesinthefunctiondefinition,thatresolvetovariablesinan
enclosingcontext)createaclosure,asnotonlythefunctionitself,butalsoitsenvironment(of
variables)mustbereturned,andthenpotentiallycalledinadifferentcontext.Thisrequires
significantlymoresupportfromthecompiler,andcancomplicateprogramanalysis.

Filescope
AscopingrulelargelyparticulartoC(andC++)isfilescope,wherescopeofvariablesand
functionsdeclaredatthetoplevelofafile(notwithinanyfunction)isfortheentirefileor
ratherforC,fromthedeclarationuntiltheendofthesourcefile,ormorepreciselytranslation
unit(internallinking).Thiscanbeseenasaformofmodulescope,wheremodulesareidentified

https://en.wikipedia.org/wiki/Scope_(computer_science)

9/24

1/10/2017

Scope(computerscience)Wikipedia

withfiles,andinmoremodernlanguagesisreplacedbyanexplicitmodulescope.Duetothe
presenceofincludestatements,whichaddvariablesandfunctionstotheinternalcontextand
maythemselvescallfurtherincludestatements,itcanbedifficulttodeterminewhatisincontext
inthebodyofafile.
IntheCcodesnippetabove,thefunctionnamesum_of_squareshasfilescope.

Modulescope
Inmodularprogramming,thescopeofanamecanbeanentiremodule,howeveritmaybe
structuredacrossvariousfiles.Inthisparadigm,modulesarethebasicunitofacomplex
program,astheyallowinformationhidingandexposingalimitedinterface.Modulescopewas
pioneeredintheModulafamilyoflanguages,andPython(whichwasinfluencedbyModula)isa
representativecontemporaryexample.
Insomeobjectorientedprogramminglanguagesthatlackdirectsupportformodules,suchas
C++,asimilarstructureisinsteadprovidedbytheclasshierarchy,whereclassesarethebasic
unitoftheprogram,andaclasscanhaveprivatemethods.Thisisproperlyunderstoodinthe
contextofdynamicdispatchratherthannameresolutionandscope,thoughtheyoftenplay
analogousroles.Insomecasesboththesefacilitiesareavailable,suchasinPython,whichhas
bothmodulesandclasses,andcodeorganization(asamodulelevelfunctionoraconventionally
privatemethod)isachoiceoftheprogrammer.

Globalscope
Adeclarationhasglobalscopeifithaseffectthroughoutanentireprogram.Variablenameswith
globalscopecalledglobalvariablesarefrequentlyconsideredbadpractice,atleastin
somelanguages,duetothepossibilityofnamecollisionsandunintentionalmasking,together
withpoormodularity,andfunctionscopeorblockscopeareconsideredpreferable.However,
globalscopeistypicallyused(dependingonthelanguage)forvariousothersortsofidentifiers,
suchasnamesoffunctions,andnamesofclassesandotherdatatypes.Inthesecases
mechanismssuchasnamespacesareusedtoavoidcollisions.

Lexicalscopingvs.dynamicscoping
Theuseoflocalvariablesofvariablenameswithlimitedscope,thatonlyexistwithina
specificfunctionhelpsavoidtheriskofanamecollisionbetweentwoidenticallynamed
variables.However,therearetwoverydifferentapproachestoansweringthisquestion:What
doesitmeantobe"within"afunction?
Inlexicalscoping(orlexicalscopealsocalledstaticscopingorstaticscope),ifavariable
name'sscopeisacertainfunction,thenitsscopeistheprogramtextofthefunctiondefinition:
withinthattext,thevariablenameexists,andisboundtothevariable'svalue,butoutsidethat
text,thevariablenamedoesnotexist.Bycontrast,indynamicscoping(ordynamicscope),ifa
variablename'sscopeisacertainfunction,thenitsscopeisthetimeperiodduringwhichthe

https://en.wikipedia.org/wiki/Scope_(computer_science)

10/24

1/10/2017

Scope(computerscience)Wikipedia

functionisexecuting:whilethefunctionisrunning,thevariablenameexists,andisboundtoits
value,butafterthefunctionreturns,thevariablenamedoesnotexist.Thismeansthatiffunction
finvokesaseparatelydefinedfunctiong,thenunderlexicalscoping,functiongdoesnothave
accesstof'slocalvariables(assumingthetextofgisnotinsidethetextoff),whileunder
dynamicscoping,functiongdoeshaveaccesstof'slocalvariables(sincegisinvokedduringthe
invocationoff).
Consider,forexample,theprogramontheright.Thefirst
$x=1
line,x=1,createsaglobalvariablexandinitializesitto1.
$functiong(){echo$x;x=2;}
Thesecondline,functiong(){echo$x;x=2;},
$functionf(){localx=3;g;}
$f#doesthisprint1,or3?
definesafunctiongthatprintsout("echoes")thecurrent
3
valueofx,andthensetsxto2(overwritingtheprevious
$echo$x#doesthisprint1,or2?
1
value).Thethirdline,functionf(){localx=3;g;}
definesafunctionfthatcreatesalocalvariablex(hidingthe
identicallynamedglobalvariable)andinitializesitto3,andthencallsg.Thefourthline,f,calls
f.Thefifthline,echo$x,printsoutthecurrentvalueofx.
So,whatexactlydoesthisprogramprint?Itdependsonthescopingrules.Ifthelanguageofthis
programisonethatuseslexicalscoping,thengprintsandmodifiestheglobalvariablex
(becausegisdefinedoutsidef),sotheprogramprints1andthen2.Bycontrast,ifthislanguage
usesdynamicscoping,thengprintsandmodifiesf'slocalvariablex(becausegiscalledfrom
withinf),sotheprogramprints3andthen1.(Asithappens,thelanguageoftheprogramis
Bash,whichusesdynamicscopingsotheprogramprints3andthen1.)

Lexicalscoping
Withlexicalscope,anamealwaysreferstoits(moreorless)locallexicalenvironment.Thisisa
propertyoftheprogramtextandismadeindependentoftheruntimecallstackbythelanguage
implementation.Becausethismatchingonlyrequiresanalysisofthestaticprogramtext,this
typeofscopingisalsocalledstaticscoping.LexicalscopingisstandardinallALGOLbased
languagessuchasPascal,Modula2andAdaaswellasinmodernfunctionallanguagessuchas
MLandHaskell.ItisalsousedintheClanguageanditssyntacticandsemanticrelatives,
althoughwithdifferentkindsoflimitations.Staticscopingallowstheprogrammertoreason
aboutobjectreferencessuchasparameters,variables,constants,types,functions,etc.assimple
namesubstitutions.Thismakesitmucheasiertomakemodularcodeandreasonaboutit,since
thelocalnamingstructurecanbeunderstoodinisolation.Incontrast,dynamicscopeforcesthe
programmertoanticipateallpossibledynamiccontextsinwhichthemodule'scodemaybe
invoked.
Forexample,considerthePascalprogramfragmentatright.The
variableIisvisibleatallpoints,becauseitisneverhiddenbyanother
variableofthesamename.ThecharvariableKisvisibleonlyinthe
mainprogrambecauseitishiddenbytherealvariableKvisiblein
procedureBandConly.VariableLisalsovisibleonlyinprocedureBand

https://en.wikipedia.org/wiki/Scope_(computer_science)

programA;
varI:integer;
K:char;

procedureB;
varK:real;

11/24

1/10/2017

Scope(computerscience)Wikipedia

Cbutitdoesnothideanyothervariable.VariableMisonlyvisiblein

procedureCandthereforenotaccessibleeitherfromprocedureBorthe
mainprogram.Also,procedureCisvisibleonlyinprocedureBandcan
thereforenotbecalledfromthemainprogram.
TherecouldhavebeenanotherprocedureCdeclaredintheprogram
outsideofprocedureB.Theplaceintheprogramwhere"C"is
mentionedthendetermineswhichofthetwoproceduresnamedCit
represents,thuspreciselyanalogouswiththescopeofvariables.

L:integer;

procedureC;
varM:real;
begin
(*scopeA+B+C*)
end;

(*scopeA+B*)
end;

(*scopeA*)
end.

Correctimplementationofstaticscopeinlanguageswithfirstclass
nestedfunctionsisnottrivial,asitrequireseachfunctionvaluetocarrywithitarecordofthe
valuesofthevariablesthatitdependson(thepairofthefunctionandthisenvironmentiscalled
aclosure).Dependingonimplementationandcomputerarchitecture,variablelookupmay
becomeslightlyinefficientwhenverydeeplylexicallynestedfunctionsareused,althoughthere
arewellknowntechniquestomitigatethis.[7][8]Also,fornestedfunctionsthatonlyrefertotheir
ownargumentsand(immediately)localvariables,allrelativelocationscanbeknownatcompile
time.Nooverheadatallisthereforeincurredwhenusingthattypeofnestedfunction.Thesame
appliestoparticularpartsofaprogramwherenestedfunctionsarenotused,and,naturally,to
programswritteninalanguagewherenestedfunctionsarenotavailable(suchasintheC
language).

History
LexicalscopingwasusedforALGOLandhasbeenpickedupinmostotherlanguagessince
then.[4]Deepbinding,whichapproximatesstatic(lexical)scoping,wasintroducedinLISP1.5
(viatheFunargdevicedevelopedbySteveRussell,workingunderJohnMcCarthy).Theoriginal
Lispinterpreter(1960)andmostearlyLispsuseddynamicscoping,butdescendantsof
dynamicallyscopedlanguagesoftenadoptstaticscopingCommonLispandScheme(withSRFI
15)havebothdynamicandstaticscoping.Perlisanotherlanguagewithdynamicscopingthat
addedstaticscopingafterwards.LanguageslikePascalandChavealwayshadlexicalscoping,
sincetheyarebothinfluencedbytheideasthatwentintoALGOL60(althoughCdidnotinclude
lexicallynestedfunctions).
Theterm"lexicalscope"datesatleastto1967,[9]whiletheterm"lexicalscoping"datesatleast
to1970,whereitwasusedinProjectMACtodescribethescopingrulesoftheLispdialectMDL
(thenknownas"Muddle").[10]

Dynamicscoping
Withdynamicscope,aglobalidentifierreferstotheidentifierassociatedwiththemostrecent
environment,andisuncommoninmodernlanguages.[4]Intechnicalterms,thismeansthateach
identifierhasaglobalstackofbindings.Introducingalocalvariablewithnamexpushesa

https://en.wikipedia.org/wiki/Scope_(computer_science)

12/24

1/10/2017

Scope(computerscience)Wikipedia

bindingontotheglobalxstack(whichmayhavebeenempty),whichispoppedoffwhenthe
controlflowleavesthescope.Evaluatingxinanycontextalwaysyieldsthetopbinding.Note
thatthiscannotbedoneatcompiletimebecausethebindingstackonlyexistsatruntime,which
iswhythistypeofscopingiscalleddynamicscoping.
Generally,certainblocksaredefinedtocreatebindingswhoselifetimeistheexecutiontimeof
theblockthisaddssomefeaturesofstaticscopingtothedynamicscopingprocess.However,
sinceasectionofcodecanbecalledfrommanydifferentlocationsandsituations,itcanbe
difficulttodetermineattheoutsetwhatbindingswillapplywhenavariableisused(orifone
existsatall).Thiscanbebeneficialapplicationoftheprincipleofleastknowledgesuggeststhat
codeavoiddependingonthereasonsfor(orcircumstancesof)avariable'svalue,butsimplyuse
thevalueaccordingtothevariable'sdefinition.Thisnarrowinterpretationofshareddatacan
provideaveryflexiblesystemforadaptingthebehaviorofafunctiontothecurrentstate(or
policy)ofthesystem.However,thisbenefitreliesoncarefuldocumentationofallvariablesused
thiswayaswellasoncarefulavoidanceofassumptionsaboutavariable'sbehavior,anddoesnot
provideanymechanismtodetectinterferencebetweendifferentpartsofaprogram.Dynamic
scopingalsovoidsallthebenefitsofreferentialtransparency.Assuch,dynamicscopingcanbe
dangerousandfewmodernlanguagesuseit.Somelanguages,likePerlandCommonLisp,allow
theprogrammertochoosestaticordynamicscopingwhendefiningorredefiningavariable.
ExamplesoflanguagesthatusedynamicscopingincludeLogo,Emacslisp,andtheshell
languagesbash,dash,andPowerShell.
Dynamicscopingisfairlyeasytoimplement.Tofindanidentifier'svalue,theprogramcould
traversetheruntimestack,checkingeachactivationrecord(eachfunction'sstackframe)fora
valuefortheidentifier.Inpractice,thisismademoreefficientviatheuseofanassociationlist,
whichisastackofname/valuepairs.Pairsarepushedontothisstackwheneverdeclarationsare
made,andpoppedwhenevervariablesgooutofscope.[11]Shallowbindingisanalternative
strategythatisconsiderablyfaster,makinguseofacentralreferencetable,whichassociates
eachnamewithitsownstackofmeanings.Thisavoidsalinearsearchduringruntimetofinda
particularname,butcareshouldbetakentoproperlymaintainthistable.[11]Notethatbothof
thesestrategiesassumealastinfirstout(LIFO)orderingtobindingsforanyonevariablein
practiceallbindingsaresoordered.
Anevensimplerimplementationistherepresentationofdynamicvariableswithsimpleglobal
variables.Thelocalbindingisperformedbysavingtheoriginalvalueinananonymouslocation
onthestackthatisinvisibletotheprogram.Whenthatbindingscopeterminates,theoriginal
valueisrestoredfromthislocation.Infact,dynamicscopeoriginatedinthismanner.Early
implementationsofLispusedthisobviousstrategyforimplementinglocalvariables,andthe
practicesurvivesinsomedialectswhicharestillinuse,suchasGNUEmacsLisp.Lexicalscope
wasintroducedintoLisplater.Thisisequivalenttotheaboveshallowbindingscheme,except
thatthecentralreferencetableissimplytheglobalvariablebindingenvironment,inwhichthe
currentmeaningofthevariableisitsglobalvalue.Maintainingglobalvariablesisn'tcomplex.
Forinstance,asymbolobjectcanhaveadedicatedslotforitsglobalvalue.

https://en.wikipedia.org/wiki/Scope_(computer_science)

13/24

1/10/2017

Scope(computerscience)Wikipedia

Dynamicscopingprovidesanexcellentabstractionforthreadlocalstorage,butifitisusedthat
wayitcannotbebasedonsavingandrestoringaglobalvariable.Apossibleimplementation
strategyisforeachvariabletohaveathreadlocalkey.Whenthevariableisaccessed,thethread
localkeyisusedtoaccessthethreadlocalmemorylocation(bycodegeneratedbythecompiler,
whichknowswhichvariablesaredynamicandwhicharelexical).Ifthethreadlocalkeydoes
notexistforthecallingthread,thenthegloballocationisused.Whenavariableislocallybound,
thepriorvalueisstoredinahiddenlocationonthestack.Thethreadlocalstorageiscreated
underthevariable'skey,andthenewvalueisstoredthere.Furthernestedoverridesofthe
variablewithinthatthreadsimplysaveandrestorethisthreadlocallocation.Whentheinitial,
outermostoverride'sscopeterminates,thethreadlocalkeyisdeleted,exposingtheglobal
versionofthevariableonceagaintothatthread.

Macroexpansion
Inmodernlanguages,macroexpansioninapreprocessorisakeyexampleofdefactodynamic
scope.Themacrolanguageitselfonlytransformsthesourcecode,withoutresolvingnames,but
sincetheexpansionisdoneinplace,whenthenamesintheexpandedtextarethenresolved
(notablyfreevariables),theyareresolvedbasedonwheretheyareexpanded(loosely"called"),
asifdynamicscopingwereoccurring.
TheCpreprocessor,usedformacroexpansion,hasdefactodynamicscope,asitdoesnotdo
nameresolutionbyitself.Forexample,themacro:
#defineADD_A(x)x+a

willexpandtoaddatothepassedvariable,withthisidentifieronlylaterresolvedbythe
compilerbasedonwherethemacroADD_Ais"called"(properly,expanded),isindynamicscope,
andisindependentofwherethemacroisdefined.Properly,theCpreprocessoronlydoeslexical
analysis,expandingthemacroduringthetokenizationstage,butnotparsingintoasyntaxtreeor
doingnameresolution.
Forexample,inthefollowingcode,theainthemacroisresolved(afterexpansion)tothelocal
variableattheexpansionsite:
#defineADD_A(x)x+a
voidadd_one(int*x){
constinta=1;
*x=ADD_A(*x);
}
voidadd_two(int*x){
constinta=2;
*x=ADD_A(*x);
}

https://en.wikipedia.org/wiki/Scope_(computer_science)

14/24

1/10/2017

Scope(computerscience)Wikipedia

Qualifiedidentifiers
Aswehaveseen,oneofthekeyreasonsforscopeisthatithelpspreventnamecollisions,by
allowingidenticalidentifierstorefertodistinctthings,withtherestrictionthattheidentifiers
musthaveseparatescopes.Sometimesthisrestrictionisinconvenientwhenmanydifferent
thingsneedtobeaccessiblethroughoutaprogram,theygenerallyallneedidentifierswithglobal
scope,sodifferenttechniquesarerequiredtoavoidnamecollisions.
Toaddressthis,manylanguagesoffermechanismsfororganizingglobalidentifiers.Thedetails
ofthesemechanisms,andthetermsused,dependonthelanguagebutthegeneralideaisthata
groupofidentifierscanitselfbegivenanameaprefixand,whennecessary,anentitycan
bereferredtobyaqualifiedidentifierconsistingoftheidentifierplustheprefix.Normallysuch
identifierswillhave,inasense,twosetsofscopes:ascope(usuallytheglobalscope)inwhich
thequalifiedidentifierisvisible,andoneormorenarrowerscopesinwhichtheunqualified
identifier(withouttheprefix)isvisibleaswell.Andnormallythesegroupscanthemselvesbe
organizedintogroupsthatis,theycanbenested.
Althoughmanylanguagessupportthisconcept,thedetailsvarygreatly.Somelanguageshave
mechanisms,suchasnamespacesinC++andC#,thatservealmostexclusivelytoenableglobal
identifierstobeorganizedintogroups.Otherlanguageshavemechanisms,suchaspackagesin
AdaandstructuresinStandardML,thatcombinethiswiththeadditionalpurposeofallowing
someidentifierstobevisibleonlytoothermembersoftheirgroup.Andobjectoriented
languagesoftenallowclassesorsingletonobjectstofulfillthispurpose(whetherornottheyalso
haveamechanismforwhichthisistheprimarypurpose).Furthermore,languagesoftenmeld
theseapproachesforexample,Perl'spackagesarelargelysimilartoC++'snamespaces,but
optionallydoubleasclassesforobjectorientedprogrammingandJavaorganizesitsvariables
andfunctionsintoclasses,butthenorganizesthoseclassesintoAdalikepackages.

Bylanguage
Scopingrulesforrepresentativelanguagesfollow.

C
InC,scopeistraditionallyknownaslinkageorvisibility,particularlyforvariables.Cisa
lexicallyscopedlanguagewithglobalscope(knownasexternallinkage),aformofmodule
scopeorfilescope(knownasinternallinkage),andlocalscope(withinafunction)withina
functionscopescanfurtherbenestedviablockscope.However,standardCdoesnotsupport
nestedfunctions.
Thelifetimeandvisibilityofavariablearedeterminedbyitsstorageclass.Therearethreetypes
oflifetimesinC:static(programexecution),automatic(blockexecution,allocatedonthestack),
andmanual(allocatedontheheap).Onlystaticandautomaticaresupportedforvariablesand
handledbythecompiler,whilemanuallyallocatedmemorymustbetrackedmanuallyacross

https://en.wikipedia.org/wiki/Scope_(computer_science)

15/24

1/10/2017

Scope(computerscience)Wikipedia

differentvariables.TherearethreelevelsofvisibilityinC:externallinkage(global),internal
linkage(roughlyfile),andblockscope(whichincludesfunctions)blockscopescanbenested,
anddifferentlevelsofinternallinkageispossiblebyuseofincludes.InternallinkageinCis
visibilityatthetranslationunitlevel,namelyasourcefileafterbeingprocessedbytheC
preprocessor,notablyincludingallrelevantincludes.
Cprogramsarecompiledasseparateobjectfiles,whicharethenlinkedintoanexecutableor
libraryviaalinker.Thusnameresolutionissplitacrossthecompiler,whichresolvesnames
withinatranslationunit(moreloosely,"compilationunit",butthisisproperlyadifferent
concept),andthelinker,whichresolvesnamesacrosstranslationunitsseelinkageforfurther
discussion.
InC,variableswithblockscopeenterscopewhentheyaredeclared(notatthetopoftheblock),
moveoutofscopeifany(nonnested)functioniscalledwithintheblock,movebackintoscope
whenthefunctionreturns,andmoveoutofscopeattheendoftheblock.Inthecaseof
automaticlocalvariables,theyarealsoallocatedondeclarationanddeallocatedattheendofthe
block,whileforstaticlocalvariables,theyareallocatedatprograminitializationanddeallocated
atprogramtermination.
Thefollowingprogramdemonstratesavariablewithblockscopecomingintoscopepartway
throughtheblock,thenexitingscope(andinfactbeingdeallocated)whentheblockends:
#include<stdio.h>
intmain(void)
{
charx='m';
printf("%c\n",x);
{
printf("%c\n",x);
charx='b';
printf("%c\n",x);
}
printf("%c\n",x);
}

ThereareotherlevelsofscopeinC.[12]Variablenamesusedinafunctionprototypehave
functionprototypevisibility,andexitscopeattheendofthefunctionprototype.Sincethename
isnotused,thisisnotusefulforcompilation,butmaybeusefulfordocumentation.Labelnames
forGOTOstatementhavefunctionscope,whilecaselabelnamesforswitchstatementshave
blockscope(theblockoftheswitch).

C++
Allthevariablesthatweintendtouseinaprogrammusthavebeendeclaredwithitstype
specifierinanearlierpointinthecode,likewedidinthepreviouscodeatthebeginningofthe
bodyofthefunctionmainwhenwedeclaredthata,b,andresultwereoftypeint.Avariablecan

https://en.wikipedia.org/wiki/Scope_(computer_science)

16/24

1/10/2017

Scope(computerscience)Wikipedia

beeitherofglobalorlocalscope.Aglobalvariableisavariabledeclaredinthemainbodyofthe
sourcecode,outsideallfunctions,whilealocalvariableisonedeclaredwithinthebodyofa
functionorablock.
Modernversionsallownestedlexicalscoping.

Go
Goislexicallyscopedusingblocks.[3]

Java
Javaislexicallyscoped.
AJavaclasscancontainthreetypesofvariables:[13]
Localvariablesaredefinedinsideamethod,oraparticularblock.Thesevariablesarelocalto
wheretheyweredefinedandlowerlevels.Forexample,aloopinsideamethodcanusethat
method'slocalvariables,butnottheotherwayaround.Theloop'svariables(localtothatloop)
aredestroyedassoonastheloopends.
Membervariables,alsocalledfieldsarevariablesdeclaredwithintheclass,outsideofany
method.Bydefault,thesevariablesareavailableforallmethodswithinthatclassandalsoforall
classesinthepackage.
Parametersarevariablesinmethoddeclarations.
Ingeneral,asetofbracketsdefinesaparticularscope,butvariablesattoplevelwithinaclass
candifferintheirbehaviordependingonthemodifierkeywordsusedintheirdefinition.The
followingtableshowstheaccesstomemberspermittedbyeachmodifier.[14]
Modifier

Class Package Subclass World

public

Yes

Yes

Yes

Yes

protected

Yes

Yes

Yes

No

(nomodifier) Yes

Yes

No

No

private

No

No

No

Yes

JavaScript
JavaScripthassimplescopingrules,[15]butvariableinitializationandnameresolutionrulescan
causeproblems,andthewidespreaduseofclosuresforcallbacksmeansthelexicalenvironment
ofafunctionwhendefined(whichisusedfornameresolution)canbeverydifferentfromthe

https://en.wikipedia.org/wiki/Scope_(computer_science)

17/24

1/10/2017

Scope(computerscience)Wikipedia

lexicalenvironmentwhenitiscalled(whichisirrelevantfornameresolution).JavaScriptobjects
havenameresolutionforproperties,butthisisaseparatetopic.
JavaScripthaslexicalscoping[16]nestedatthefunctionlevel,withtheglobalscopebeingthe
outermostscope.Thisscopingisusedforbothvariablesandforfunctions(meaningfunction
declarations,asopposedtovariablesoffunctiontype).[17]Blockscopingissupportedwiththe
letandconstkeywordsinMozillasinceJavaScript1.7,[18]andAsof2013,isproposedindrafts
ofECMAScript6,butisnotcurrentlypartofthestandard.Blockscopingcanbeproducedby
wrappingtheentireblockinafunctionandthenexecutingitthisisknownastheimmediately
invokedfunctionexpression(IIFE)pattern.
WhileJavaScriptscopingissimplelexical,functionleveltheassociatedinitializationand
nameresolutionrulesareacauseofconfusion.Firstly,assignmenttoanamenotinscope
defaultstocreatinganewglobalvariable,notalocalone.Secondly,tocreateanewlocal
variableonemustusethevarkeywordthevariableisthencreatedatthetopofthefunction,
withvalueundefinedandthevariableisassigneditsvaluewhentheassignmentexpressionis
reached:
AvariablewithanInitialiserisassignedthevalueofitsAssignmentExpressionwhenthe
VariableStatementisexecuted,notwhenthevariableiscreated.[19]
Thisisknownasvariablehoisting[20]thedeclaration,butnottheinitialization,ishoistedtothe
topofthefunction.Thirdly,accessingvariablesbeforeinitializationyieldsundefined,ratherthan
asyntaxerror.Fourthly,forfunctiondeclarations,thedeclarationandtheinitializationareboth
hoistedtothetopofthefunction,unlikeforvariableinitialization.Forexample,thefollowing
codeproducesadialogwithoutputundefined,asthelocalvariabledeclarationishoisted,
shadowingtheglobalvariable,buttheinitializationisnot,sothevariableisundefinedwhen
used:
a=1;
functionf(){
alert(a);
vara=2;
}
f();

Further,asfunctionsarefirstclassobjectsinJavaScriptandarefrequentlyassignedascallbacks
orreturnedfromfunctions,whenafunctionisexecuted,thenameresolutiondependsonwhereit
wasoriginallydefined(thelexicalenvironmentofthedefinition),notthelexicalenvironmentor
executionenvironmentwhereitiscalled.Thenestedscopesofaparticularfunction(frommost
globaltomostlocal)inJavaScript,particularlyofaclosure,usedasacallback,aresometimes
referredtoasthescopechain,byanalogywiththeprototypechainofanobject.

https://en.wikipedia.org/wiki/Scope_(computer_science)

18/24

1/10/2017

Scope(computerscience)Wikipedia

ClosurescanbeproducedinJavaScriptbyusingnestedfunctions,asfunctionsarefirstclass
objects.[21]Returninganestedfunctionfromanenclosingfunctionincludesthelocalvariablesof
theenclosingfunctionasthe(nonlocal)lexicalenvironmentofthereturnedfunction,yieldinga
closure.Forexample:
functionnewCounter(){
//returnacounterthatisincrementedoncall(startingat0)
//andwhichreturnsitsnewvalue
vara=0;
varb=function(){a++;returna;};
returnb;
}
c=newCounter();
alert(c()+''+c());//outputs"12"

ClosuresarefrequentlyusedinJavaScript,duetobeingusedforcallbacks.Indeed,anyhooking
ofafunctioninthelocalenvironmentasacallbackorreturningitfromafunctioncreatesa
closureifthereareanyunboundvariablesinthefunctionbody(withtheenvironmentofthe
closurebasedonthenestedscopesofthecurrentlexicalenvironment,or"scopechain")this
maybeaccidental.Whencreatingacallbackbasedonparameters,theparametersmustbestored
inaclosure,otherwiseitwillaccidentallycreateaclosurethatreferstothevariablesinthe
enclosingenvironment,whichmaychange.[22]
NameresolutionofpropertiesofJavaScriptobjectsisbasedoninheritanceintheprototypetree
apathtotherootinthetreeiscalledaprototypechainandisseparatefromnameresolution
ofvariablesandfunctions.

Lisp
Lispdialectshavevariousrulesforscoping.TheoriginalLispuseddynamicscopingitwas
Schemethatintroducedstatic(lexical)scopingtotheLispfamily.CommonLispadoptedlexical
scopingfromScheme,asdidClojure,butsomeotherdialectsofLisp,likeEmacsLisp,stilluse
dynamicscoping.

Python
Forvariables,Pythonhasfunctionscope,modulescope,andglobalscope.Namesenterscopeat
thestartofacontext(function,module,orglobally),andexitscopewhenanonnestedfunction
iscalledorthecontextends.Ifanameisusedpriortovariableinitialization,thisraisesaruntime
exception.Ifavariableissimplyaccessed(notassignedto)inacontext,nameresolutionfollows
theLEGBrule(Local,Enclosing,Global,Builtin).However,ifavariableisassignedto,it
defaultstocreatingalocalvariable,whichisinscopefortheentirecontext.Boththeserulescan
beoverriddenwithaglobalornonlocal(inPython3)declarationpriortouse,whichallows
accessingglobalvariablesevenifthereisaninterveningnonlocalvariable,andassigningto
globalornonlocalvariables.

https://en.wikipedia.org/wiki/Scope_(computer_science)

19/24

1/10/2017

Scope(computerscience)Wikipedia

Asasimpleexample,afunctionresolvesavariabletotheglobalscope:
>>>deff():
...print(x)
...
>>>x='global'
>>>f()
global

Notethatxisinitializedbeforefiscalled,sonoerrorisraised,eventhoughitisdeclaredafterf
isdeclared.Lexicallythisisaforwardreference,whichisallowedinPython.
Hereassignmentcreatesanewlocalvariable,whichdoesnotchangethevalueoftheglobal
variable:
>>>deff():
...x='f'
...print(x)
...
>>>x='global'
>>>print(x)
global
>>>f()
f
>>>print(x)
global

Assignmenttoavariablewithinafunctioncausesittobedeclaredlocaltothefunction(hence
thelocalvariableisinscopefortheentirefunction),andthususingitpriortothisassignment
raisesanerror.ThisdiffersfromC,wherethelocalvariableisonlyinscopefromitsdeclaration,
notfortheentirefunction.Thiscoderaisesanerror:
>>>deff():
...print(x)
...x='f'
...
>>>x='global'
>>>f()
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
File"<stdin>",line2,inf
UnboundLocalError:localvariable'x'referencedbeforeassignment

Thedefaultnameresolutionrulescanbeoverriddenwiththeglobalornonlocal(inPython3)
keywords.Inthebelowcode,theglobalxdeclarationingmeansthatxresolvestotheglobal
variable.Itthuscanbeaccessed(asithasalreadybeeninitialized),andassignmentassignstothe
globalvariable,ratherthandeclaringanewlocalvariable.Notethatnoglobaldeclarationis
neededinfsinceitdoesnotassigntothevariable,itdefaultstoresolvingtotheglobal
variable.

https://en.wikipedia.org/wiki/Scope_(computer_science)

20/24

1/10/2017

Scope(computerscience)Wikipedia

>>>deff():
...print(x)
...
>>>defg():
...globalx
...print(x)
...x='g'
...
>>>x='global'
>>>f()
global
>>>g()
global
>>>f()
g

globalcanalsobeusedfornestedfunctions.Inadditiontoallowingassignmenttoaglobal

variable,asinanunnestedfunction,thiscanalsobeusedtoaccesstheglobalvariableinthe
presenceofanonlocalvariable:
>>>x='global'
>>>deff():
...defg():
...globalx
...print(x)
...x='f'
...g()
...
>>>f()
global

Fornestedfunctions,thereisalsothenonlocaldeclaration,forassigningtoanonlocalvariable,
similartousingglobalinanunnestedfunction:
>>>deff():
...defg():
...nonlocalx#Python3.xonly
...x='g'
...x='f'
...g()
...print(x)
...
>>>x='global'
>>>f()
g
>>>print(x)
global

R
Risalexicallyscopedlanguage,unlikeotherimplementationsofSwherethevaluesoffree
variablesaredeterminedbyasetofglobalvariables,whileinRtheyaredeterminedbythe
environmentinwhichthefunctionwascreated.[23]Thescopingenvironmentsmaybeaccessed

https://en.wikipedia.org/wiki/Scope_(computer_science)

21/24

1/10/2017

Scope(computerscience)Wikipedia

usingavarietyoffeatures(suchasparent.frame())whichcansimulatetheexperienceof
dynamicscopingshouldtheprogrammerdesire.

Seealso
Closure(computerscience)
Globalvariable
Localvariable
Letexpression
Nonlocalvariable
Namebinding
Nameresolution(programminglanguages)
Variables(scopeandextent)
Informationhiding
ImmediatelyinvokedfunctionexpressionsinJavascript

Notes
a.Seedefinitionformeaningof"scope"versus"context".
b."Dynamicscope"basesnameresolutiononextent(lifetime),notscope,andthusisformally
inaccurate.
c.Forexample,theJinjatemplateengineforPythonbydefaultusesbothlexicalscoping(forimports)
anddynamicscoping(forincludes),andallowsbehaviortobespecifiedwithkeywordsseeImport
ContextBehavior(http://jinja.pocoo.org/docs/templates/#importcontextbehavior).
d."Nameresolution"and"namebinding"arelargelysynonymousnarrowlyspeaking"resolution"
determineswhichnameaparticularuseofanamerefersto,withoutassociatingitwithanymeaning,
asinhigherorderabstractsyntaxwhile"binding"associatesthenamewithanactualmeaning.In
practicethetermsareusedinterchangeably.
e.Forselfmodifyingcodethelexicalcontextitselfcanchangeduringruntime.
f.Bycontrast,*"avariableisinscope",*"avariable'scontext"or*"avariablegoingoutofscope"are
allincorrectavariablehasscope,whileaprogramhascontext.

References
1."ReportontheAlgorithmicLanguageAlgol60",2.7.Quantities,kindsandscopes
2.WG14N1256(http://www.openstd.org/jtc1/sc22/wg14/www/docs/n1256.pdf)(2007updatedversion
oftheC99standard),6.2.1Scopesofidentifiers,20070907
3.TheGoProgrammingLanguageSpecification(http://golang.org/ref/spec):Declarationsandscope(htt
p://golang.org/ref/spec#Declarations_and_scope),VersionofNov13,2013
4.BorningA.CSE341LexicalandDynamicScoping(https://web.archive.org/web/20150207225438/
http://courses.cs.washington.edu/courses/cse341/08au/generalconcepts/scoping.html).Universityof
Washington.
5.Crockford,Douglas."CodeConventionsfortheJavaScriptProgrammingLanguage".Retrieved
20150104.
6.Backus,J.W.Wegstein,J.H.VanWijngaarden,A.Woodger,M.Bauer,F.L.Green,J.Katz,
C.McCarthy,J.Perlis,A.J.Rutishauser,H.Samelson,K.Vauquois,B.(1960)."Reportonthe

https://en.wikipedia.org/wiki/Scope_(computer_science)

22/24

1/10/2017

Scope(computerscience)Wikipedia

algorithmiclanguageALGOL60".CommunicationsoftheACM.3(5):299.
doi:10.1145/367236.367262.
7."ProgrammingLanguagePragmatics(http://booksite.elsevier.com/9780123745149/appendices/data/ch
apters/3a_impsc.pdf)",LeBlankCooksymboltable
8."ASymbolTableAbstractiontoImplementLanguageswithExplicitScopeControl(http://originww
w.computer.org/csdl/trans/ts/1983/01/01703006.pdf)",LeBlankCook,1983
9."lexicalscope(https://books.google.com/books?id=qk0jAQAAMAAJ&q=%22lexical+scope%22)",
ComputerandProgramOrganization,Part3(https://books.google.com/books?id=qk0jAQAAMAAJ
&pg=PA18),p.18,atGoogleBooks,UniversityofMichigan.EngineeringSummerConferences,
1967
10."lexicalscoping(https://books.google.com/books?id=m0IdAQAAMAAJ&q=%22lexical+scoping%2
2)",ProjectMACProgressReport,Volume8(https://books.google.com/books?id=m0IdAQAAMAAJ
&pg=PA80),p.80,atGoogleBooks,1970.
11.Scott2009,3.4ImplementingScope,p.143.
12."Scope(http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlc
pp8l.doc%2Flanguage%2Fref%2Fzexscope_c.htm)",XLC/C++V8.0forLinux,IBM
13.https://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
14.https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
15."EverythingyouneedtoknowaboutJavascriptvariablescope(http://www.coolcoder.in/2014/03/ever
ythingyouneedtoknowabout.html)",SaurabParakh(http://www.coolcoder.in/p/aboutus.html),
CodingisCool(http://www.coolcoder.in/),20100208
16.10.2LexicalEnvironments(http://es5.github.io/#x10.2)
17.Functionsandfunctionscope(https://developer.mozilla.org/enUS/docs/JavaScript/Reference/Functio
ns_and_function_scope)
18."let(https://developer.mozilla.org/enUS/docs/JavaScript/Reference/Statements/let)",JavaScript
Reference
19."12.2VariableStatement(http://es5.github.io/#x12.2)",AnnotatedECMAScript5.1,Lastupdated:
20120528
20."JavaScriptScopingandHoisting(http://www.adequatelygood.com/JavaScriptScopingandHoisting.
html)",BenCherry(http://www.adequatelygood.com/about.html),AdequatelyGood(http://www.ade
quatelygood.com/),20100208
21.JavascriptClosures(http://jibbering.com/faq/notes/closures/),RichardCornford.March2004
22."ExplainingJavaScriptScopeAndClosures(http://robertnyman.com/2008/10/09/explainingjavascrip
tscopeandclosures/)",RobertNyman,October9,2008
23.RFAQ:Lexicalscoping(https://cran.rproject.org/doc/FAQ/RFAQ.html#Lexicalscoping)
Abelson,HaroldSussman,GeraldJaySussman,Julie(1996)[1984].StructureandInterpretation
ofComputerPrograms.Cambridge,MA:MITPress.ISBN0262510871.
"Lexicaladdressing"(http://mitpress.mit.edu/sicp/fulltext/book/bookZH35.html#%_sec_5.
5.6)
Scott,MichaelL.(2009)[2000].ProgrammingLanguagePragmatics(Thirded.).Morgan
KaufmannPublishers.ISBN9780123745149.
Chapter3:Names,Scopes,andBindings,pp.111174
Section13.4.1:ScriptingLanguages:InnovativeFeatures:NamesandScopes,pp.691699

Retrievedfrom"https://en.wikipedia.org/w/index.php?
title=Scope_(computer_science)&oldid=753892005"
Categories: Programminglanguageconcepts

https://en.wikipedia.org/wiki/Scope_(computer_science)

23/24

1/10/2017

Scope(computerscience)Wikipedia

Thispagewaslastmodifiedon9December2016,at19:18.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicenseadditional
termsmayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.
WikipediaisaregisteredtrademarkoftheWikimediaFoundation,Inc.,anonprofit
organization.

https://en.wikipedia.org/wiki/Scope_(computer_science)

24/24

You might also like