Tải bản đầy đủ - 0 (trang)
Chapter 12. Storage Classes, Linkage, and Memory Management

Chapter 12. Storage Classes, Linkage, and Memory Management

Tải bản đầy đủ - 0trang

StorageClasses

Cprovidesfivedifferentmodels,orstorageclasses,for

variables.There'salsoasixthmodel,basedonpointers,that

we'llgettolaterinthischapter(inthesection"Allocated

Memory:malloc()andfree()").Youcandescribeavariable(or,

moregenerally,adataobject)intermsofitsstorageduration,

whichishowlongitstaysinmemory,anditsscopeandits

linkage,whichtogetherindicatewhichpartsofaprogramcan

useitbyname.Thedifferentstorageclassesofferdifferent

combinationsofscope,linkage,andstorageduration.Youcan

havevariablesthatcanbesharedoverseveralfilesofsource

code,variablesthatcanbeusedbyanyfunctioninone

particularfile,variablesthatcanbeusedonlywithinaparticular

function,andevenvariablesthatcanbeusedonlywithina

subsectionofafunction.Youcanhavevariablesthatexistfor

thedurationofaprogramandvariablesthatexistonlywhile

thefunctioncontainingthemisexecuting.Youalsocanstore

datainmemorythatisallocatedandfreedexplicitlybymeans

offunctioncalls.

Beforeexaminingthefivestorageclasses,weneedto

investigatethemeaningofthetermsscope,linkage,and

storageduration.Afterthat,we'llreturntothespecificstorage

classes.



Scope

Scopedescribestheregionorregionsofaprogramthatcan

accessanidentifier.ACvariablehasoneofthefollowing

scopes:blockscope,functionprototypescope,orfilescope.

Theprogramexamplestodatehaveusedblockscope.Ablock,

asyou'llrecall,isaregionofcodecontainedwithinanopening

braceandthematchingclosingbrace.Forinstance,theentire



bodyofafunctionisablock.Anycompoundstatementwithina

functionalsoisablock.Avariabledefinedinsideablockhas

blockscope,anditisvisiblefromthepointitisdefineduntilthe

endoftheblockcontainingthedefinition.Also,formalfunction

parameters,eventhoughtheyoccurbeforetheopeningbrace

ofafunction,haveblockscopeandbelongtotheblock

containingthefunctionbody.Sothelocalvariableswe'veused

todate,includingformalfunctionparameters,haveblockscope.

Therefore,thevariablescleoandpatrickinthefollowingcode

bothhaveblockscopeextendingtotheclosingbrace:



doubleblocky(doublecleo)

{

doublepatrick=0.0;

...

returnpatrick;

}



Variablesdeclaredinaninnerblockhavescoperestrictedjust

tothatblock:



doubleblocky(doublecleo)

{

doublepatrick=0.0;

inti;

for(i=0;i<10;i++)

{

doubleq=cleo*i;//startofscopeforq

...

patrick*=q;

}//endofscopeforq

...

returnpatrick;

}



Inthisexample,thescopeofqislimitedtotheinnerblock,and

onlycodewithinthatblockcanaccessq.



Traditionally,variableswithblockscopehadtobedeclaredat

thebeginningofablock.C99hasrelaxedthatrule,allowing

youtodeclarevariablesanywhereinablock.Onenew

possibilityisinthecontrolsectionofaforloop.Thatis,you

nowcandothis:



for(inti=0;i<10;i++)

printf("AC99feature:i=%d",i);



Aspartofthisnewfeature,C99expandstheconceptofablock

toincludethecodecontrolledbyaforloop,whileloop,do

whileloop,orifstatement,evenifnobracketsareused.Soin

thepreviousforloop,thevariableiisconsideredtobepartof

theforloopblock.Therefore,itsscopeislimitedtothefor

loop.Afterexecutionleavestheforloop,theprogramwillno

longerseethati.

Functionprototypescopeappliestovariablenamesusedin

functionprototypes,asinthefollowing:



intmighty(intmouse,doublelarge);



Functionprototypescoperunsfromthepointthevariableis

definedtotheendoftheprototypedeclaration.Whatthis

meansisthatallthecompilercaresaboutwhenhandlinga

functionprototypeargumentisthetypes;thenamesyouuse,if

any,normallydon'tmatter,andtheyneedn'tmatchthenames

youuseinthefunctiondefinition.Onecaseinwhichthenames

matteralittleiswithvariable-lengtharrayparameters:



voiduse_a_VLA(intn,intm,ar[n][m]);



Ifyouusenamesinthebrackets,theyhavetobenames

declaredearlierintheprototype.

Avariablewithitsdefinitionplacedoutsideofanyfunctionhas

filescope.Avariablewithfilescopeisvisiblefromthepointitis

definedtotheendofthefilecontainingthedefinition.Takea

lookatthisexample:



#include

intunits=0;/*avariablewithfilescope*/

voidcritic(void);

intmain(void)

{

...

}



voidcritic(void)

{

...

}



Here,thevariableunitshasfilescope,anditcanbeusedin

bothmain()andcritic().Becausetheycanbeusedinmore

thanonefunction,filescopevariablesarealsocalledglobal

variables.

Thereisoneothertypeofscope,calledfunctionscope,butit

appliesonlytolabelsusedbygotostatements.Functionscope



meansagotolabelinaparticularfunctionisvisibletocode

anywhereinthatfunction,regardlessoftheblockinwhichit

appears.



Linkage

Next,let'slookatlinkage.ACvariablehasoneofthefollowing

linkages:externallinkage,internallinkage,ornolinkage.

Variableswithblockscopeorprototypescopehavenolinkage.

Thatmeanstheyareprivatetotheblockorprototypeinwhich

theyaredefined.Avariablewithfilescopecanhaveeither

internalorexternallinkage.Avariablewithexternallinkagecan

beusedanywhereinamultifileprogram.Avariablewith

internallinkagecanbeusedanywhereinasinglefile.

Sohowcanyoutellwhetherafilescopevariablehasinternalor

externallinkage?Youlooktoseeifthestorageclassspecifier

staticisusedintheexternaldefinition:



intgiants=5;//filescope,externallinkage

staticintdodgers=3;//filescope,internallinkage

intmain()

{

...



}

...



Thevariablegiantscanbeusedbyotherfilesthatarepartof

thesameprogram.Thedodgersvariableisprivatetothis

particularfile,butcanbeusedbyanyfunctioninthefile.



StorageDuration

ACvariablehasoneofthefollowingtwostoragedurations:

staticstoragedurationorautomaticstorageduration.Ifa

variablehasstaticstorageduration,itexiststhroughout

programexecution.Variableswithfilescopehavestaticstorage

duration.Notethatforfilescopevariables,thekeywordstatic

indicatesthelinkagetype,notthestorageduration.Afilescope

variabledeclaredusingstatichasinternallinkage,butallfile

scopevariables,usinginternallinkageorexternallinkage,have

staticstorageduration.

Variableswithblockscopenormallyhaveautomaticstorage

duration.Thesevariableshavememoryallocatedforthem

whentheprogramenterstheblockinwhichtheyaredefined,

andthememoryisfreedwhentheblockisexited.Theideais

thatmemoryusedforautomaticvariablesisaworkspaceor

scratchpadthatcanbereused.Forexample,afterafunction

callterminates,thememoryitusedforitsvariablescanbe

usedtoholdvariablesforthenextfunctionthatiscalled.

Thelocalvariableswe'veusedsofarfallintotheautomatic

category.Forexample,inthefollowingcode,thevariables

numberandindexcomeintobeingeachtimethebore()

functioniscalledandpassawayeachtimethefunction



completes:



voidbore(intnumber)

{

intindex;

for(index=0;index


puts("Theydon'tmakethemthewaytheyusedto.\n");

return0;

}



Cusesscope,linkage,andstoragedurationtodefinefive

storageclasses:automatic,register,staticwithblockscope,

staticwithexternallinkage,andstaticwithinternallinkage.

Table12.1liststhecombinations.Nowthatwe'vecovered

scope,linkage,andstorageduration,wecandiscussthese

storageclassesinmoredetail.

Table12.1.TheFiveStorageClasses

StorageClass Duration



Scope



Linkage



How

Declared



automatic



Automatic



Block



None



Inablock



register



Automatic



Block



None



Inablockwith

thekeyword

register



staticwith

external

linkage



Static



File



External



Outsideofall

functions



staticwith

internal

linkage



Static



File



Internal



Outsideofall

functionswith

thekeyword

static



Block



None



Inablockwith

thekeyword

static



staticwithno Static

linkage



AutomaticVariables

Avariablebelongingtotheautomaticstorageclasshas

automaticstorageduration,blockscope,andnolinkage.By

default,anyvariabledeclaredinablockorfunctionheader

belongstotheautomaticstorageclass.Youcan,however,make

yourintentionsperfectlyclearbyexplicitlyusingthekeyword

auto,asshownhere:



intmain(void)



{

autointplox;



Youmightdothis,forexample,todocumentthatyouare

intentionallyoverridinganexternalfunctiondefinitionorthatit

isimportantnottochangethevariabletoanotherstorageclass.

Thekeywordautoistermedastorageclassspecifier.

Blockscopeandnolinkageimpliesthatonlytheblockinwhich

thevariableisdefinedcanaccessthatvariablebyname.(Of

course,argumentscanbeusedtocommunicatethevariable's

valueandaddresstoanotherfunction,butthatisindirect

knowledge.)Anotherfunctioncanuseavariablewiththesame

name,butitwillbeanindependentvariablestoredina

differentmemorylocation.

Recallthatautomaticstoragedurationmeansthatthevariable

comesintoexistencewhentheprogramenterstheblockthat

containsthevariabledeclaration.Whentheprogramexitsthe

block,theautomaticvariabledisappears.Itsmemorylocation

cannowbeusedforsomethingelse.

Let'slookmorecloselyatnestedblocks.Avariableisknown

onlytotheblockinwhichitisdeclaredandtoanyblockinside

thatblock:



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Storage Classes, Linkage, and Memory Management

Tải bản đầy đủ ngay(0 tr)

×