What is the difference between char * const and const char
文章推薦指數: 80 %
Difference between char* and const char*? - Stack Overflow
Resultsfromthe2022DeveloperSurveyarenowavailable
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
Whatisthedifferencebetweenchar*constandconstchar*?
AskQuestion
Asked
13years,1monthago
Modified
2years,6monthsago
Viewed
234ktimes
344
196
What'sthedifferencebetween:
char*const
and
constchar*
cpointersconstants
Share
Follow
editedNov27,2012at15:46
amiregelz
1,67777goldbadges2323silverbadges3939bronzebadges
askedMay20,2009at22:16
LB.LB.
13.1k2323goldbadges6565silverbadges102102bronzebadges
5
4
PossibleduplicateofWhatisthedifferencebetweenconstint*,constint*const,andintconst*?
– emlai
Feb14,2016at13:07
13
Thefirstthingtotheleftofthe"const"iswhat'sconstant.If"const"isthethingthefarthesttotheleft,thenthefirstthingtotherightofitiswhat'sconstant.
– Cupcake
Jul31,2016at4:43
8
Asafriendlytip,neverforgetthatcdeclisathing.
– BradenBest
Jun16,2018at7:42
Thereisanothercharconst*whichisthereturntypeofexception::what()
– Zhang
Jul22,2019at3:14
2
ISOC++FAQ:What’sthedifferencebetween“constX*p”,“X*constp”and“constX*constp”?
– legends2k
Sep21,2020at16:25
Addacomment
|
19Answers
19
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
430
Thedifferenceisthatconstchar*isapointertoaconstchar,whilechar*constisaconstantpointertoachar.
Thefirst,thevaluebeingpointedtocan'tbechangedbutthepointercanbe.Thesecond,thevaluebeingpointedatcanchangebutthepointercan't(similartoareference).
Thereisalsoa
constchar*const
whichisaconstantpointertoaconstantchar(sonothingaboutitcanbechanged).
Note:
Thefollowingtwoformsareequivalent:
constchar*
and
charconst*
TheexactreasonforthisisdescribedintheC++standard,butit'simportanttonoteandavoidtheconfusion.Iknowseveralcodingstandardsthatprefer:
charconst
over
constchar
(withorwithoutpointer)sothattheplacementoftheconstelementisthesameaswithapointerconst.
Share
Follow
editedFeb28,2014at12:02
answeredMay20,2009at22:21
workmad3workmad3
24.6k44goldbadges3434silverbadges5656bronzebadges
9
9
Woulditbeworthwhiletonotewhathappensifmultiplevariablesarespecifiedinthesamedeclaration?Ibelieveconstint*foo,*bar;woulddeclarebothfooandbartobeintconst*,butintconst*foo,*barwoulddeclarefootobeaintconst*andbartobeint*.Ithinktypedefint*intptr;constintptrfoo,bar;woulddeclarebothvariablestobeint*const;Idon'tknowanywaytouseacombineddeclarationtocreatetwovariablesofthattypewithoutatypedef.
– supercat
Apr12,2013at21:57
2
@supercatIbelieveconstint*foo,*bar;woulddeclarebothfooandbartobeintconst*:Yes.butintconst*foo,*barwoulddeclarefootobeaintconst*andbartobeint*:No!Itwouldbeexactlythesameasthepreviouscase.(Seeideone.com/RsaB7nwhereyougetthesameerrorforbothfooandbar).Ithinktypedefint*intptr;constintptrfoo,bar;woulddeclarebothvariablestobeint*const:Yes.Idon'tknowanywaytouseacombineddeclarationtocreatetwovariablesofthattypewithoutatypedef:Well,int*constfoo,*constbar;.Cdeclaratorsyntax...
– gx_
Aug28,2013at18:35
@gx_:SoIwaswrong--myuncertaintywaswhyIsuggestedthatitmightbehelpfultosaywhattherulesare.Whatwouldintconst*foo,*volatilebardotobar?Makeitbothconstandvolatile?ImissPascal'scleanseparationofdeclared-variablenamesandtheirtypes(apointertoanarrayofpointerstointegerswouldbevarfoo:^Array[3..4]of^Integer;`.That'dbesomefunnynestedparenthesizedthinginC,Ithink.
– supercat
Aug28,2013at18:54
4
@supercat(oh,C-only,sorryfortheC++codelink,IgotherefromaC++question)It'sallabouttheCdeclarationsyntax,witha("pure")typepartfollowedbyadeclarator.In"intconst*foo,*volatilebar"thetypepartisintconst(stopsbeforethe*)andthedeclaratorsare*foo(theexpression*foowilldenoteanintconst)and*volatilebar;readingright-to-left(goodruleforcv-qualifiers),fooisapointertoaconstint,andbarisavolatilepointertoaconstint(thepointeritselfisvolatile,thepointedintis[accessedas]const).
– gx_
Aug28,2013at21:23
1
@supercatAndasfor"apointertoanarrayofpointerstointegers"(Idon'tknowPascal,notsureaboutthe[3..4]syntax,solet'stakeanarrayof10elements):int*(*foo)[10];.Itmirrorsits(future)useasanexpression:*(*foo)[i](withianintegerintherange[0,10)i.e.[0,9])willfirstdereferencefootogetatthearray,thenaccesstheelementatindexi(becausepostfix[]bindstighterthanprefix*),thendereferencethiselement,finallyyieldinganint(seeideone.com/jgjIjR).Buttypedefmakesiteasier(seeideone.com/O3wb7d).
– gx_
Aug28,2013at21:25
|
Show4morecomments
130
Toavoidconfusion,alwaysappendtheconstqualifier.
int*mutable_pointer_to_mutable_int;
intconst*mutable_pointer_to_constant_int;
int*constconstant_pointer_to_mutable_int;
intconst*constconstant_pointer_to_constant_int;
Share
Follow
answeredMay21,2009at0:08
diapirdiapir
2,66211goldbadge1717silverbadges2424bronzebadges
12
11
Why?"Toavoidconfusion"doesn'texplainwhattheconfusionistome.
– AndrewWeir
Nov20,2013at11:48
20
@Andrew:Iwashintingatconsistencyandthusreadability.Writingalltypequalifierssotheymodifywhat'sontheirleft,always,iswhatIuse.
– diapir
Nov20,2013at14:31
2
Actuallyit'sthebestansweronthesubjectI'vefoundinSO
– Trap
Apr22,2014at15:51
8
Asacodestandard,Ihaverarelyencounteredthisstyleandsoamnotlikelytoadoptit.Howeverasalearningtool,thisanswerwasveryhelpful!(SoIguesstoobadthisisn'tmorecommonstyle.)
– natevw
Sep29,2014at21:33
10
@Alla:pdoesn'trelatetothetype:(constint*const).Forbetterorworse(worseifyouaskme)theconstqualifier,bothinCandC++,ismeanttobepostfix:cfconstmemberfunctionvoidfoo(inta)const;.Thepossibilitytodeclareconstintistheexceptionratherthantherule.
– diapir
Apr9,2015at7:17
|
Show7morecomments
57
constalwaysmodifiesthethingthatcomesbeforeit(totheleftofit),EXCEPTwhenit'sthefirstthinginatypedeclaration,whereitmodifiesthethingthatcomesafterit(totherightofit).
Sothesetwoarethesame:
intconst*i1;
constint*i2;
theydefinepointerstoaconstint.Youcanchangewherei1andi2points,butyoucan'tchangethevaluetheypointat.
This:
int*consti3=(int*)0x12345678;
definesaconstpointertoanintegerandinitializesittopointatmemorylocation12345678.Youcanchangetheintvalueataddress12345678,butyoucan'tchangetheaddressthati3pointsto.
Share
Follow
answeredMay20,2009at22:36
DonMcCaugheyDonMcCaughey
9,05233goldbadges2929silverbadges3636bronzebadges
0
Addacomment
|
26
constchar*isapointertoaconstantcharacter
char*constisaconstantpointertoacharacter
constchar*constisaconstantpointertoaconstantcharacter
Share
Follow
editedJan13,2012at15:19
answeredMay20,2009at22:20
AndrewColesonAndrewColeson
9,91288goldbadges3030silverbadges3030bronzebadges
0
Addacomment
|
23
const*charisinvalidCcodeandismeaningless.Perhapsyoumeanttoaskthedifferencebetweenaconstchar*andacharconst*,orpossiblythedifferencebetweenaconstchar*andachar*const?
Seealso:
Whatareconstpointers(asopposedtopointerstoconstobjects)?
ConstinC
DifferencebetweenconstdeclarationsinC++
C++constquestion
WhycanIchangethevaluesofaconstchar*variable?
Share
Follow
editedJun20,2020at9:12
CommunityBot
111silverbadge
answeredMay20,2009at22:22
AdamRosenfieldAdamRosenfield
376k9696goldbadges502502silverbadges583583bronzebadges
0
Addacomment
|
21
Ruleofthumb:readthedefinitionfromrighttoleft!
constint*foo;
Means"foopoints(*)toanintthatcannotchange(const)".
Totheprogrammerthismeans"Iwillnotchangethevalueofwhatfoopointsto".
*foo=123;orfoo[0]=123;wouldbeinvalid.
foo=&bar;isallowed.
int*constfoo;
Means"foocannotchange(const)andpoints(*)toanint".
Totheprogrammerthismeans"Iwillnotchangethememoryaddressthatfoorefersto".
*foo=123;orfoo[0]=123;isallowed.
foo=&bar;wouldbeinvalid.
constint*constfoo;
Means"foocannotchange(const)andpoints(*)toanintthatcannotchange(const)".
Totheprogrammerthismeans"Iwillnotchangethevalueofwhatfoopointsto,norwillIchangetheaddressthatfoorefersto".
*foo=123;orfoo[0]=123;wouldbeinvalid.
foo=&bar;wouldbeinvalid.
Share
Follow
answeredJul8,2016at0:59
Mr.LlamaMr.Llama
19.4k22goldbadges5454silverbadges108108bronzebadges
Addacomment
|
11
constchar*xHereXisbasicallyacharacterpointerwhichispointingtoaconstantvalue
char*constxisrefertocharacterpointerwhichisconstant,butthelocationitispointingcanbechange.
constchar*constxiscombinationto1and2,meansitisaconstantcharacterpointerwhichispointingtoconstantvalue.
const*charxwillcauseacompilererror.itcannotbedeclared.
charconst*xisequaltopoint1.
theruleofthumbisifconstiswithvarnamethenthepointerwillbeconstantbutthepointinglocationcanbechanged,elsepointerwillpointtoaconstantlocationandpointercanpointtoanotherlocationbutthepointinglocationcontentcannotbechange.
Share
Follow
editedJun5,2019at22:49
EvanCarroll
72.1k4444goldbadges236236silverbadges406406bronzebadges
answeredJul4,2012at18:19
AAnkitAAnkit
26.8k1212goldbadges5757silverbadges7070bronzebadges
1
2
"char*constxisrefertocharacterpointerwhichisconstant,butthelocationitispointingcanbechange."Wrong.Thevalueatthelocationcanbechangednotthelocationitself.
– PleaseHelp
Mar12,2015at13:44
Addacomment
|
5
Anotherthumbruleistocheckwhereconstis:
before*=>valuestoredisconstant
after*=>pointeritselfisconstant
Share
Follow
answeredJan25,2013at9:43
AadishriAadishri
1,23122goldbadges1818silverbadges2626bronzebadges
Addacomment
|
4
Firstoneisasyntaxerror.Maybeyoumeantthedifferencebetween
constchar*mychar
and
char*constmychar
Inthatcase,thefirstoneisapointertodatathatcan'tchange,andthesecondoneisapointerthatwillalwayspointtothesameaddress.
Share
Follow
answeredMay20,2009at22:21
JavierJavier
4,46266goldbadges3535silverbadges4545bronzebadges
Addacomment
|
4
Lotsofanswerprovidespecifictechniques,ruleofthumbsetctounderstandthisparticularinstanceofvariabledeclaration.Butthereisagenerictechniqueofunderstandanydeclaration:
Clockwise/SpiralRule
A)
constchar*a;
Aspertheclockwise/spiralruleaispointertocharacterthatisconstant.Whichmeanscharacterisconstantbutthepointercanchange.i.e.a="otherstring";isfinebuta[2]='c';willfailtocompile
B)
char*consta;
Aspertherule,aisconstpointertoacharacter.i.e.Youcandoa[2]='c';butyoucannotdoa="otherstring";
Share
Follow
answeredApr14,2017at18:01
JamesWebbTelescopeAlienJamesWebbTelescopeAlien
3,18322goldbadges2525silverbadges4848bronzebadges
3
2
Alsoknownasright-leftrule(atleastthat'showIlearntit):jdurrett.ba.ttu.edu/3345/handouts/RL-rule.html
– TomasPruzina
May9,2018at12:05
1
(Wouldbemuchbetteriftheessenceoftheanswerwouldnotbehiddenbehindalink,withthetextherenotevenciting,oratleastreferring,toanyofitsspecifics,beyondageneric"aspertherule".)
– Sz.
Jul14,2019at9:58
@Sz.DoyouhaveanyspecificconfusionherethatIcanclear?Thereisreallynotmuchtoitafterknowingtherule.
– JamesWebbTelescopeAlien
Jul15,2019at1:53
Addacomment
|
2
char*constandconstchar*?
Pointingtoaconstantvalue
constchar*p;//valuecannotbechanged
Constantpointertoavalue
char*constp;//addresscannotbechanged
Constantpointertoaconstantvalue
constchar*constp;//bothcannotbechanged.
Share
Follow
editedNov27,2015at11:03
answeredNov27,2015at10:49
YogeeshHTYogeeshHT
2,4512020silverbadges1717bronzebadges
Addacomment
|
1
Ipresumeyoumeanconstchar*andchar*const.
Thefirst,constchar*,isapointertoaconstantcharacter.Thepointeritselfismutable.
Thesecond,char*constisaconstantpointertoacharacter.Thepointercannotchange,thecharacteritpointstocan.
Andthenthereisconstchar*constwherethepointerandcharactercannotchange.
Share
Follow
answeredMay20,2009at22:21
MichaelMichael
53k55goldbadges118118silverbadges142142bronzebadges
1
Yourfirsttwoareactuallythesameandyourthirdisacompilererror:)
– workmad3
May20,2009at22:22
Addacomment
|
1
Hereisadetailedexplanationwithcode
/*constchar*p;
char*constp;
constchar*constp;*///thesearethethreeconditions,
//constchar*p;constchar*constp;pointervaluecannotbechanged
//char*constp;pointeraddresscannotbechanged
//constchar*constp;bothcannotbechanged.
#include