Está en la página 1de 12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

const(computerprogramming)
FromWikipedia,thefreeencyclopedia

IntheC,C++,andDprogramminglanguages,constisatypequalifier:[a]akeywordappliedtoadata
typethatindicatesthatthedataisconstant(doesnotvary).Whilethiscanbeusedtodeclareconstants,
constintheCfamilyoflanguagesdiffersfromsimilarconstructsinotherlanguagesinbeingpartofthe
type,andthushascomplicatedbehaviorwhencombinedwithpointers,references,compositedatatypes,
andtypechecking.

Contents
1 Introduction
2 Consequences
3 Otheruses
4 Syntax
4.1 Simpledatatypes
4.2 Pointersandreferences
4.2.1 Cconvention
4.2.2 C++convention
4.3 Parametersandvariables
5 C++
5.1 Methods
6 Loopholestoconstcorrectness
7 Problems
7.1 strchrproblem
8 D
9 History
10 Otherlanguages
11 Seealso
12 Notes
13 References

https://en.wikipedia.org/wiki/Const_(computer_programming)

1/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

13 References
14 Externallinks

Introduction
Whenappliedinanobjectdeclaration,[b]itindicatesthattheobjectisaconstant:itsvaluedoesnot
change,unlikeavariable.Thisbasicusetodeclareconstantshasparallelsinmanyotherlanguages.
However,unlikeinotherlanguages,intheCfamilyoflanguagestheconstispartofthetype,notpartof
theobject.Forexample,inC,constintx=1;declaresanobjectxofconstinttypetheconstis
partofthetype,asifitwereparsed(constint)xwhileinAda,X:constantINTEGER:=1_declares
aconstant(akindofobject)XofINTEGERtype:theconstantispartoftheobject,butnotpartofthetype.
Thishastwosubtleresults.Firstly,constcanbeappliedtopartsofamorecomplextypeforexample,
intconst*constx;declaresaconstantpointertoaconstantinteger,whileintconst*x;declaresa
variablepointertoaconstantinteger,andint*constx;declaresaconstantpointertoavariable
integer.Secondly,becauseconstispartofthetype,itmustmatchaspartoftypechecking.Forexample,
thefollowingcodeisinvalid:
voidf(int&x);
//...
constinti;
f(i);

becausetheargumenttofmustbeavariableinteger,butiisaconstantinteger.Thismatchingisaform
ofprogramcorrectness,andisknownasconstcorrectness.Thisallowsaformofprogrammingby
contract,wherefunctionsspecifyaspartoftheirtypesignaturewhethertheymodifytheirargumentsor
not,andwhethertheirreturnvalueismodifiableornot.Thistypecheckingisprimarilyofinterestin
pointersandreferencesnotbasicvaluetypeslikeintegersbutalsoforcompositedatatypesor
templatedtypessuchascontainers.Itisconcealedbythefactthattheconstcanoftenbeomitted,dueto
typecoercion(implicittypeconversion)andCbeingcallbyvalue(C++andDareeithercallbyvalue
orcallbyreference).

Consequences
Theideaofconstnessdoesnotimplythatthevariableasitisstoredinthecomputer'smemoryis
unwritable.Rather,constnessisacompiletimeconstructthatindicateswhataprogrammershoulddo,
notnecessarilywhattheycando.Note,however,thatinthecaseofpredefineddata(suchasconstchar
*stringliterals),Cconstisoftenunwritable.

Otheruses
Inaddition,a(nonstatic)memberfunctioncanbedeclaredasconst.Inthiscase,thethispointerinside
suchafunctionisoftypereturn_value_typeconst*constratherthanmerelyoftype
return_value_type*const.Thismeansthatnonconstfunctionsforthisobjectcannotbecalledfrom
insidesuchafunction,norcanmembervariablesbemodified.InC++,amembervariablecanbe
declaredasmutable,indicatingthatthisrestrictiondoesnotapplytoit.Insomecases,thiscanbeuseful,
https://en.wikipedia.org/wiki/Const_(computer_programming)

2/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

forexamplewithcaching,referencecounting,anddatasynchronization.Inthesecases,thelogical
meaning(state)oftheobjectisunchanged,buttheobjectisnotphysicallyconstantsinceitsbitwise
representationmaychange.

Syntax
InC,C++,andD,alldatatypes,includingthosedefinedbytheuser,canbedeclaredconst,andconst
correctnessdictatesthatallvariablesorobjectsshouldbedeclaredassuchunlesstheyneedtobe
modified.Suchproactiveuseofconstmakesvalues"easiertounderstand,track,andreasonabout,"[1]
anditthusincreasesthereadabilityandcomprehensibilityofcodeandmakesworkinginteamsand
maintainingcodesimplerbecauseitcommunicatesinformationaboutavalue'sintendeduse.Thiscan
helpthecompileraswellasthedeveloperwhenreasoningaboutcode.Itcanalsoenableanoptimizing
compilertogeneratemoreefficientcode.[2]

Simpledatatypes
Forsimplenonpointerdatatypes,applyingtheconstqualifierisstraightforward.Itcangooneitherside
ofthetypeforhistoricalreasons(thatis,constcharfoo='a';isequivalenttocharconstfoo=
'a';).Onsomeimplementations,usingconstonbothsidesofthetype(forinstance,constcharconst)
generatesawarningbutnotanerror.

Pointersandreferences
Forpointerandreferencetypes,themeaningofconstismorecomplicatedeitherthepointeritself,or
thevaluebeingpointedto,orboth,canbeconst.Further,thesyntaxcanbeconfusing.Apointercanbe
declaredasaconstpointertowritablevalue,orawritablepointertoaconstvalue,orconstpointerto
constvalue.Aconstpointercannotbereassignedtopointtoadifferentobjectfromtheoneitisinitially
assigned,butitcanbeusedtomodifythevaluethatitpointsto(calledthepointee).Referencevariables
arethusanalternatesyntaxforconstpointers.Apointertoaconstobject,ontheotherhand,canbe
reassignedtopointtoanothermemorylocation(whichshouldbeanobjectofthesametypeorofa
convertibletype),butitcannotbeusedtomodifythememorythatitispointingto.Aconstpointertoa
constobjectcanalsobedeclaredandcanneitherbeusedtomodifythepointeenorbereassignedto
pointtoanotherobject.Thefollowingcodeillustratesthesesubtleties:
voidFoo(int*ptr,
intconst*ptrToConst,
int*constconstPtr,
intconst*constconstPtrToConst)
{
*ptr=0;//OK:modifiesthe"pointee"data
ptr=NULL;//OK:modifiesthepointer
*ptrToConst=0;//Error!Cannotmodifythe"pointee"data
ptrToConst=NULL;//OK:modifiesthepointer
*constPtr=0;//OK:modifiesthe"pointee"data
constPtr=NULL;//Error!Cannotmodifythepointer
*constPtrToConst=0;//Error!Cannotmodifythe"pointee"data
constPtrToConst=NULL;//Error!Cannotmodifythepointer
}

Cconvention
https://en.wikipedia.org/wiki/Const_(computer_programming)

3/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

FollowingusualCconventionfordeclarations,declarationfollowsuse,andthe*inapointeriswritten
onthepointer,indicatingdereferencing.Forexample,inthedeclarationint*ptr,thedereferencedform
*ptrisanint,whilethereferenceformptrisapointertoanint.Thusconstmodifiesthenametoits
right.TheC++conventionisinsteadtoassociatethe*withthetype,asinint*ptr,andreadtheconst
asmodifyingthetypetotheleft.intconst*ptrToConstcanthusbereadas"*ptrToConstisaint
const"(thevalueisconstant),or"ptrToConstisaintconst*"(thepointerisapointertoaconstant
integer).Thus:
int*ptr;//*ptrisanintvalue
intconst*ptrToConst;//*ptrToConstisaconstant(int:integervalue)
int*constconstPtr;//constPtrisaconstant(int*:integerpointer)
intconst*constconstPtrToConst;//constPtrToConstisaconstant(pointer)
//asis*constPtrToConst(value)

C++convention
FollowingC++conventionofanalyzingthetype,notthevalue,aruleofthumbistoreadthedeclaration
fromrighttoleft.Thus,everythingtotheleftofthestarcanbeidentifiedasthepointeetypeand
everythingtotherightofthestararethepointerproperties.Forinstance,inourexampleabove,int
const*canbereadasawritablepointerthatreferstoanonwritableinteger,andint*constcanbe
readasanonwritablepointerthatreferstoawritableinteger.
C/C++alsoallowstheconsttobeplacedtotheleftofthetype,inthefollowingsyntax:
constint*ptrToConst;//identicalto:intconst*ptrToConst,
constint*constconstPtrToConst;//identicalto:intconst*constconstPtrToConst

Thismoreclearlyseparatesthetwolocationsfortheconst,andallowsthe*toalwaysbeboundtoits
precedingtype,thoughitstillrequiresreadingrighttoleft,asfollows:
int*ptr;
constint*ptrToConst;//(constint)*,notconst(int*)
int*constconstPtr;
constint*constconstPtrToConst;

Note,however,thatdespitethedifferentconventionforformattingC++code,thesemanticsofpointer
declarationarethesame:
int*a;//aisanintpointer
int*a,b;//TRICKY:aisanintpointerasabove,butbisnot;bisanintvalue
int*a,*b;//bothaandbarepointers;*aand*bareintvalues

BjarneStroustrup'sFAQrecommendsonlydeclaringonevariableperlineifusingtheC++convention,
toavoidthisissue.[3]
C++referencesfollowsimilarrules.Adeclarationofaconstreferenceisredundantsincereferencescan
neverbemadetorefertoanotherobject:
inti=22;
intconst&refToConst=i;//OK
int&constconstRef=i;//Errorthe"const"isredundant
https://en.wikipedia.org/wiki/Const_(computer_programming)

4/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Evenmorecomplicateddeclarationscanresultwhenusingmultidimensionalarraysandreferences(or
pointers)topointershowever,somehavearguedthattheseareconfusinganderrorproneandthatthey
thereforeshouldgenerallybeavoidedorreplacedwithhigherlevelstructures.

Parametersandvariables
constcanbedeclaredbothonfunctionparametersandonvariables(staticorautomatic,includingglobal

orlocal).Theinterpretationvariesbetweenuses.Aconststaticvariable(globalvariableorstaticlocal
variable)isaconstant,andmaybeusedfordatalikemathematicalconstants,suchasconstdoublePI=
3.14159realisticallylonger,oroverallcompiletimeparameters.Aconstautomaticvariable(non
staticlocalvariable)meansthatsingleassignmentishappening,thoughadifferentvaluemaybeused
eachtime,suchasconstintx_squared=x*x.Aconstparameterinpassbyreferencemeansthatthe
referencedvalueisnotmodifieditispartofthecontractwhileaconstparameterinpassbyvalue
(orthepointeritself,inpassbyreference)doesnotaddanythingtotheinterface(asthevaluehasbeen
copied),butindicatesthatinternally,thefunctiondoesnotmodifytheparameter(itisasingle
assignment).Forthisreason,somefavorusingconstinparametersonlyforpassbyreference,whereit
changesthecontract,butnotforpassbyvalue,whereitexposestheimplementation.

C++
Methods
Inordertotakeadvantageofthedesignbycontractapproachforuserdefinedtypes(structsandclasses),
whichcanhavemethodsaswellasmemberdata,theprogrammermusttaginstancemethodsasconstif
theydon'tmodifytheobject'sdatamembers.Applyingtheconstqualifiertoinstancemethodsthusisan
essentialfeatureforconstcorrectness,andisnotavailableinmanyotherobjectorientedlanguagessuch
asJavaandC#orinMicrosoft'sC++/CLIorManagedExtensionsforC++.Whileconstmethodscanbe
calledbyconstandnonconstobjectsalike,nonconstmethodscanonlybeinvokedbynonconst
objects.Theconstmodifieronaninstancemethodappliestotheobjectpointedtobythe"this"pointer,
whichisanimplicitargumentpassedtoallinstancemethods.Thushavingconstmethodsisawayto
applyconstcorrectnesstotheimplicit"this"pointerargumentjustlikeotherarguments.
Thisexampleillustrates:
classC
{
inti;
public:
intGet()const//Notethe"const"tag
{returni;}
voidSet(intj)//Notethelackof"const"
{i=j;}
};
voidFoo(C&nonConstC,constC&constC)
{
inty=nonConstC.Get();//Ok
intx=constC.Get();//Ok:Get()isconst
nonConstC.Set(10);//Ok:nonConstCismodifiable
constC.Set(10);//Error!Set()isanonconstmethodandconstCisaconstqualifiedobject
}

https://en.wikipedia.org/wiki/Const_(computer_programming)

5/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Intheabovecode,theimplicit"this"pointertoSet()hasthetype"C*const"whereasthe"this"
pointertoGet()hastype"constC*const",indicatingthatthemethodcannotmodifyitsobjectthrough
the"this"pointer.
Oftentheprogrammerwillsupplybothaconstandanonconstmethodwiththesamename(but
possiblyquitedifferentuses)inaclasstoaccommodatebothtypesofcallers.Consider:
classMyArray
{
intdata[100];
public:
int&Get(inti){returndata[i];}
intconst&Get(inti)const{returndata[i];}
};
voidFoo(MyArray&array,MyArrayconst&constArray)
{
//Getareferencetoanarrayelement
//andmodifyitsreferencedvalue.
array.Get(5)=42;//OK!(Calls:int&MyArray::Get(int))
constArray.Get(5)=42;//Error!(Calls:intconst&MyArray::Get(int)const)
}

TheconstnessofthecallingobjectdetermineswhichversionofMyArray::Get()willbeinvokedand
thuswhetherornotthecallerisgivenareferencewithwhichhecanmanipulateoronlyobservethe
privatedataintheobject.Thetwomethodstechnicallyhavedifferentsignaturesbecausetheir"this"
pointershavedifferenttypes,allowingthecompilertochoosetherightone.(Returningaconstreference
toanint,insteadofmerelyreturningtheintbyvalue,maybeoverkillinthesecondmethod,butthe
sametechniquecanbeusedforarbitrarytypes,asintheStandardTemplateLibrary.)

Loopholestoconstcorrectness
ThereareseveralloopholestopureconstcorrectnessinCandC++.Theyexistprimarilyfor
compatibilitywithexistingcode.
Thefirst,whichappliesonlytoC++,istheuseofconst_cast,whichallowstheprogrammertostripthe
constqualifier,makinganyobjectmodifiable.Thenecessityofstrippingthequalifierariseswhenusing
existingcodeandlibrariesthatcannotbemodifiedbutwhicharenotconstcorrect.Forinstance,
considerthiscode:
//Prototypeforafunctionwhichwecannotchangebutwhich
//weknowdoesnotmodifythepointeepassedin.
voidLibraryFunc(int*ptr,intsize);
voidCallLibraryFunc(constint*ptr,intsize)
{
LibraryFunc(ptr,size);//Error!Dropsconstqualifier
int*nonConstPtr=const_cast<int*>(ptr);//Stripqualifier
LibraryFunc(nonConstPtr,size);//OK
}

However,anyattempttomodifyanobjectthatisitselfdeclaredconstbymeansofconstcastresultsin
undefinedbehavioraccordingtotheISOC++Standard.Intheexampleabove,ifptrreferencesaglobal,
local,ormembervariabledeclaredasconst,oranobjectallocatedontheheapvianewconstint,the
codeisonlycorrectifLibraryFuncreallydoesnotmodifythevaluepointedtobyptr.
https://en.wikipedia.org/wiki/Const_(computer_programming)

6/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

TheClanguagehasaneedofaloopholebecauseacertainsituationexists.Variableswithstaticstorage
durationareallowedtobedefinedwithaninitialvalue.However,theinitializercanuseonlyconstants
likestringconstantsandotherliterals,andisnotallowedtousenonconstantelementslikevariable
names,whethertheinitializerelementsaredeclaredconstornot,orwhetherthestaticdurationvariable
isbeingdeclaredconstornot.Thereisanonportablewaytoinitializeaconstvariablethathasstatic
storageduration.Bycarefullyconstructingatypecastonthelefthandsideofalaterassignment,aconst
variablecanbewrittento,effectivelystrippingawaytheconstattributeand'initializing'itwithnon
constantelementslikeotherconstvariablesandsuch.Writingintoaconstvariablethiswaymaywork
asintended,butitcausesundefinedbehaviorandseriouslycontradictsconstcorrectness:
constsize_tbufferSize=8*1024;
constsize_tuserTextBufferSize;//initialvaluedependsonconstbufferSize,can'tbeinitializedhere
...

intsetupUserTextBox(textBox_t*defaultTextBoxType,rect_t*defaultTextBoxLocation)
{
*(size_t*)&userTextBufferSize=bufferSizesizeof(structtextBoxControls);//warning:mightwork,butnotguarant
...
}

Anotherloophole[4]appliesbothtoCandC++.Specifically,thelanguagesdictatethatmemberpointers
andreferencesare"shallow"withrespecttotheconstnessoftheirownersthatis,acontainingobject
thatisconsthasallconstmembersexceptthatmemberpointees(andreferees)arestillmutable.To
illustrate,considerthisC++code:
structS
{
intval;
int*ptr;
};
voidFoo(constS&s)
{
inti=42;
s.val=i;//Error:sisconst,sovalisaconstint
s.ptr=&i;//Error:sisconst,soptrisaconstpointertoint
*s.ptr=i;//OK:thedatapointedtobyptrisalwaysmutable,
//eventhoughthisissometimesnotdesirable
}

AlthoughtheobjectspassedtoFoo()isconstant,whichmakesallofitsmembersconstant,thepointee
accessiblethroughs.ptrisstillmodifiable,thoughthismaynotbedesirablefromthestandpointof
constcorrectnessbecausesmightsolelyownthepointee.Forthisreason,Meyersarguesthatthe
defaultformemberpointersandreferencesshouldbe"deep"constness,whichcouldbeoverriddenbya
mutablequalifierwhenthepointeeisnotownedbythecontainer,butthisstrategywouldcreate
compatibilityissueswithexistingcode.Thus,forhistoricalreasons,thisloopholeremainsopeninCand
C++.
Thelatterloopholecanbeclosedbyusingaclasstohidethepointerbehindaconstcorrectinterface,
butsuchclasseseitherdon'tsupporttheusualcopysemanticsfromaconstobject(implyingthatthe
containingclasscannotbecopiedbytheusualsemanticseither)orallowotherloopholesbypermitting
thestrippingofconstnessthroughinadvertentorintentionalcopying.

https://en.wikipedia.org/wiki/Const_(computer_programming)

7/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Finally,severalfunctionsintheCstandardlibraryviolateconstcorrectness,astheyacceptaconst
pointertoacharacterstringandreturnanonconstpointertoapartofthesamestring.strtoland
strchrareamongthesefunctions.SomeimplementationsoftheC++standardlibrary,suchas
Microsoft's[5]trytoclosethisloopholebyprovidingtwooverloadedversionsofsomefunctions:a
"const"versionanda"nonconst"version.

Problems
Theuseofthetypesystemtoexpressconstancyleadstovariouscomplexitiesandproblems,andhas
accordinglybeencriticizedandnotadoptedoutsidethenarrowCfamilyofC,C++,andD.JavaandC#,
whichareheavilyinfluencedbyCandC++,bothexplicitlyrejectedconststyletypequalifiers,instead
expressingconstancybykeywordsthatapplytotheidentifier(finalinJava,constandreadonlyinC#).
EvenwithinCandC++,theuseofconstvariessignificantly,withsomeprojectsandorganizations
usingitconsistently,andothersavoidingit.
strchrproblem

Theconsttypequalifiercausesdifficultieswhenthelogicofafunctionisagnostictowhetheritsinputis
constantornot,butreturnsavaluewhichshouldbeofthesamequalifiedtypeasaninput.Inother
words,forthesefunctions,iftheinputisconstant(constqualified),thereturnvalueshouldbeaswell,
butiftheinputisvariable(notconstqualified),thereturnvalueshouldbeaswell.Becausethetype
signatureofthesefunctionsdiffers,itrequirestwofunctions(orpotentiallymore,incaseofmultiple
inputs)withthesamelogicaformofgenericprogramming.
ThisproblemarisesevenforsimplefunctionsintheCstandardlibrary,notablystrchrthisobservation
iscreditedbyRitchietoTomPluminthemid1980s.[6]Thestrchrfunctionlocatesacharacterina
stringformally,itreturnsapointertothefirstoccurrenceofthecharactercinthestrings,andinclassic
C(K&RC)itsprototypeis:
char*strchr(char*s,intc);

Thestrchrfunctiondoesnotmodifytheinputstring,butthereturnvalueisoftenusedbythecallerto
modifythestring,suchas:
if(p=strchr(q,'/'))
*p='';

Thusontheonehandtheinputstringcanbeconst(sinceitisnotmodifiedbythefunction),andifthe
inputstringisconstthereturnvalueshouldbeaswellmostsimplybecauseitmightreturnexactlythe
inputpointer,ifthefirstcharacterisamatchbutontheotherhandthereturnvalueshouldnotbeconst
iftheoriginalstringwasnotconst,sincethecallermaywishtousethepointertomodifytheoriginal
string.
InC++thisisdoneviafunctionoverloading,typicallyimplementedviaatemplate,resultingintwo
functions,sothatthereturnvaluehasthesameconstqualifiedtypeastheinput:[c]
char*strchr(char*s,intc);
constchar*strchr(constchar*s,intc);

https://en.wikipedia.org/wiki/Const_(computer_programming)

8/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Thesecaninturnbedefinedbyatemplate:
template<T>
T*strchr(T*s,intc){...}

InDthisishandledviatheinoutkeyword,whichactsasawildcardforconst,immutable,orunqualified
(variable),yielding:[7][d]
inout(char)*strchr(inout(char)*s,intc);

However,inCneitheroftheseispossible,sinceCdoesnothavefunctionoverloading,andinsteadthis
ishandledbyhavingasinglefunctionwheretheinputisconstantbuttheoutputiswritable:
char*strchr(constchar*s,intc);

ThisallowsidiomaticCcode,butdoesstriptheconstqualifieriftheinputactuallywasconstqualified,
violatingtypesafety.ThissolutionwasproposedbyRitchie,andsubsequentlyadopted.Thisdifference
isoneofthefailuresofcompatibilityofCandC++.

D
InVersion2oftheDprogramminglanguage,twokeywordsrelatingtoconstexist.[8]Theimmutable
keyworddenotesdatathatcannotbemodifiedthroughanyreference.Theconstkeyworddenotesanon
mutableviewofmutabledata.UnlikeC++const,Dconstandimmutableare"deep"ortransitive,and
anythingreachablethroughaconstorimmutableobjectisconstorimmutablerespectively.
Exampleofconstvs.immutableinD
int[]foo=newint[5];//fooismutable.
constint[]bar=foo;//barisaconstviewofmutabledata.
immutableint[]baz=foo;//Error:allviewsofimmutabledatamustbeimmutable.
immutableint[]nums=newimmutable(int)[5];//Nomutablereferencetonumsmaybecreated.
constint[]constNums=nums;//Works.immutableisimplicitlyconvertibletoconst.
int[]mutableNums=nums;//Error:Cannotcreateamutableviewofimmutabledata.

ExampleoftransitiveordeepconstinD
classFoo{
Foonext;
intnum;
}
immutableFoofoo=newimmutable(Foo);
foo.next.num=5;//Won'tcompile.foo.nextisoftypeimmutable(Foo).
//foo.next.numisoftypeimmutable(int).

History

https://en.wikipedia.org/wiki/Const_(computer_programming)

9/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

constwasintroducedbyBjarneStroustrupinCwithClasses,thepredecessortoC++,in1981,andwas
originallycalledreadonly.[9][10]Astomotivation,Stroustrupwrites:[10]

"Itservedtwofunctions:asawayofdefiningasymbolicconstantthatobeysscopeandtyperules
(thatis,withoutusingamacro)andasawayofdeeminganobjectinmemoryimmutable."
Thefirstuse,asascopedandtypedalternativetomacros,wasanalogouslyfulfilledforfunctionlike
macrosviatheinlinekeyword.Constantpointers,andthe*constnotation,weresuggestedbyDennis
Ritchieandsoadopted.[10]
constwasthenadoptedinCaspartofstandardization,andappearsinC89(andsubsequentversions)
alongwiththeothertypequalifier,volatile.[11]Afurtherqualifier,noalias,wassuggestedatthe

December1987meetingoftheX3J11committee,butwasrejecteditsgoalwasultimatelyfulfilledby
therestrictkeywordinC99.Ritchiewasnotverysupportiveoftheseadditions,arguingthattheydid
not"carrytheirweight",butultimatelydidnotarguefortheirremovalfromthestandard.[12]
DsubsequentlyinheritedconstfromC++,whereitisknownasatypeconstructor(nottypequalifier)
andaddedtwofurthertypeconstructors,immutableandinout,tohandlerelatedusecases.[e]

Otherlanguages
OtherlanguagesdonotfollowC/C++inhavingconstancypartofthetype,thoughtheyoftenhave
superficiallysimilarconstructsandmayusetheconstkeyword.Typicallythisisonlyusedforconstants
(constantobjects).
C#hasaconstkeyword,butwithradicallydifferentandsimplersemantics:itmeansacompiletime
constant,andisnotpartofthetype.
InJavatheobjectorientedkeywordfinalisusedforattributes(andthencealsoforlocalvariables),but
whileconstisareservedword,itisnotactuallyusedasakeyword,andonecannotmarkparametersas
constant.TherewasaproposaltoaddconsttoJavain1999,butthiswasrejected,notablybecause
addingitafterthefactandthenchangingthestandardlibrarytouseitconsistentlywouldhavebroken
compatibility.[13]
Javadoesnothaveconstitinsteadhasfinal,whichcanbeappliedtolocal"variable"declarationsand
appliestotheidentifier,notthetype.Ithasadifferentobjectorienteduseforobjectmembers,whichis
theoriginofthename.
Interestingly,theJavalanguagespecificationregardsconstasareservedkeywordi.e.,onethatcannot
beusedasvariableidentifierbutassignsnosemanticstoit:itisareservedword(itcannotbeusedin
identifiers)butnotakeyword(ithasnospecialmeaning).Itisthoughtthatthereservationofthe
keywordoccurredtoallowforanextensionoftheJavalanguagetoincludeC++styleconstmethods
andpointertoconsttype.Anenhancementrequestticketforimplementingconstcorrectnessexistsin
theJavaCommunityProcess,butwasclosedin2005onthebasisthatitwasimpossibletoimplementin
abackwardscompatiblefashion.[14]
ThecontemporaryAda83independentlyhadthenotionofaconstantobjectandaconstant
keyword,[15][f]withinputparametersandloopparametersbeingimplicitlyconstant.Heretheconstantis
apropertyoftheobject,notofthetype.
https://en.wikipedia.org/wiki/Const_(computer_programming)

10/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Seealso
Singleassignment
restrict
pointeraliasing

Notes
a. InDthetermtypeconstructorisusedinsteadoftypequalifier,byanalogywithconstructorsinobject
orientedprogramming.
b. Formallywhentheconstispartoftheoutermostderivedtypeinadeclarationpointerscomplicate
discussion.
c. NotethatpointerdeclarationsyntaxconventionsdifferbetweenCandC++:inCchar*sisstandard,whilein
C++char*sisstandard.
d. IdiomaticDcodewoulduseanarrayhereinsteadofapointer.[7]
e. Dalsointroducedthesharedtypeconstructor,butthisisrelatedtousecasesofvolatile,notconst.
f. TheAdastandardcallsthisa"reservedword"seethatarticleforusage.

References
1. HerbSutterandAndreiAlexandrescu(2005).C++CodingStandards.p.30.Boston:AddisonWesley.ISBN
0321113586
2. "Whyisthekfree()argumentconst?".lkml.org.20130112.
3. http://www.stroustrup.com/bs_faq2.html#whitespace
4. ScottMeyers(2005).EffectiveC++,ThirdEdition.pp.2123.Boston:AddisonWesley.ISBN9780321
334879
5. "strchr,wcschr,_mbschr(CRT)".Msdn.microsoft.com.Retrieved20130818.
6. http://www.lysator.liu.se/c/dmronnoalias.html
7. TheDProgrammingLanguage,AndreiAlexandrescu,8.8:PropagatingaQualifierfromParametertoResult
8. "const(FAQ)DProgrammingLanguage".Digitalmars.com.Retrieved20130818.
9. BjarneStroustrup,"ExtensionsoftheCLanguageTypeConcept.",BellLabsinternalTechnical
Memorandum,January5,1981.
10. SiblingRivalry:CandC++(http://www.stroustrup.com/sibling_rivalry.pdf),BjarneStroustrup,2002,p.5
11. DennisM.Ritchie,"TheDevelopmentoftheCLanguage(http://cm.belllabs.com/who/dmr/chist.html)",
2003:"X3J11alsointroducedahostofsmalleradditionsandadjustments,forexample,thetypequalifiers
constandvolatile,andslightlydifferenttypepromotionrules."
12. "LetmebeginbysayingthatI'mnotconvincedthateventhepreDecemberqualifiers(`const'and`volatile')
carrytheirweightIsuspectthatwhattheyaddtothecostoflearningandusingthelanguageisnotrepaidin
greaterexpressiveness.`Volatile',inparticular,isafrillforesotericapplications,andmuchbetterexpressed
byothermeans.Itschiefvirtueisthatnearlyeveryonecanforgetaboutit.`Const'issimultaneouslymore
usefulandmoreobtrusiveyoucan'tavoidlearningaboutit,becauseofitspresenceinthelibraryinterface.
Nevertheless,Idon'targuefortheextirpationofqualifiers,ifonlybecauseitistoolate."
13. JDK4211070:Javashouldsupportconstparameters(likeC++)forcodemaintainence[sic]
(http://bugs.java.com/view_bug.do?bug_id=4211070)
14. "BugID:JDK4211070Javashouldsupportconstparameters(likeC++)forcodemaintainence[sic]".
Bugs.sun.com.Retrieved20141104.
15. 1815A(http://archive.adaic.com/standards/83lrm/html/Welcome.htmlANSI/MILSTD),3.2.1.Object
Declarations(http://archive.adaic.com/standards/83lrm/html/lrm0302.html#3.2.1):
"Thedeclaredobjectisaconstantifthereservedwordconstantappearsintheobjectdeclarationthe
declarationmustthenincludeanexplicitinitialization.Thevalueofaconstantcannotbemodifiedafter
initialization.Formalparametersofmodeinofsubprogramsandentries,andgenericformalparametersof
modein,arealsoconstantsaloopparameterisaconstantwithinthecorrespondingloopasubcomponentor
sliceofaconstantisaconstant."
https://en.wikipedia.org/wiki/Const_(computer_programming)

11/12

12/11/2015

const(computerprogramming)Wikipedia,thefreeencyclopedia

Externallinks
"ConstCorrectness"(http://gotw.ca/gotw/006.htm)byHerbSutter
"ConstantOptimization?"(http://gotw.ca/gotw/081.htm)byHerbSutter
TheC++FAQLite:Constcorrectness(http://parashift.com/c++faqlite/constcorrectness.html)
byMarshallCline
Section"Valuesubstitution(http://www.mi.uni
koeln.de/c/mirror/www.codeguru.com/cpp/tic/tic_html.zip/tic0092.html)"fromthefreeelectronic
bookThinkinginC++byBruceEckel
"HereAConst,ThereAConst"(http://www.digitalmars.com/d/const.html)byWalterBright
"ConstandInvariant"fromDprogramminglanguagespecification,version2(experimental)
(http://www.digitalmars.com/d/2.0/const3.html)
SomenotesonconstcorrectnessinstraightCin"CPointerQualifiers"
(http://www.thomasstover.com/c_pointer_qualifiers.html)byThomasStover
Retrievedfrom"https://en.wikipedia.org/w/index.php?
title=Const_(computer_programming)&oldid=687517748"
Categories: Cprogramminglanguagefamily Datatypes Programminglanguagetopics
Thispagewaslastmodifiedon26October2015,at02:16.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicenseadditionalterms
mayapply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.Wikipediaisa
registeredtrademarkoftheWikimediaFoundation,Inc.,anonprofitorganization.

https://en.wikipedia.org/wiki/Const_(computer_programming)

12/12

También podría gustarte