开发者

char *p="orkut" vs const char *p="orkut"

 char *p="orkut" vs const char *p="orkut"

whats the differenc开发者_Python百科e btwn these two...

EDIT

from bjarne stroustrup,3rd edition page 90

void f()
{

char* p="plato";
p[4]='e' // error: assign to const;result is undefined

}

this kind of error cannont be general b caught until run time and implementations differ in their enforcement of this rule

Same with const char *p="plato"

Thats why iam asking the diffrence... Whats the significance of const here..


The const char* variant is correct.

You should not change memory that comes from a string literal (referred to as static storage usually). It is read only memory.

The difference is that the char* variant will allow you to write the syntax to change the data that it points to by dereferencing it. What it actually does though is undefined.

//Option 1:
char *p = "orkut";
*p = 'x';//undefined behavior


//Option 2:
const char *q = "orkut";
*q = 'x';//compiling error

I would rather have option 2 happen to me.


A declaration of const char * p means that the thing p points at is const, ie should not change. I say should not because it is possible to cast away the constness. As has been pointed out, changing a string literal is undefined and often leads to an access violation/segmentation fault.

Not this declaration is different than char * const p which means that p itself it const rather than the thing p points at.


The problem that Stroustrup discusses in what you're quoting is that in C++ a string literal will readily convert to "an rvlaue of type "pointer to char" (4.2/2 "Array-to-pointer conversion"). This is specifically so that the very common idiom of pointing a char* to a literal string wouldn't cause a bazillion programs to fail to compile. (especially when C++ was initially evolving from C).

If you can get away with declaring you pointer as char const* (or the equivalent const char*), you'll help yourself from running into problems like those described in the Stroustrup quote. However, you might well run into irritating problems using the pointer with functions that aren't 100% const correct.


See this question.

Basically,

char *p="orkut";

In this case, p is supposed to be read-only, but this is not enforced by all compilers (or the standard).


note that more recent gcc implementations will not let you do

  char *foo = "foo";

they insist on the const (certainly in -wall -werror mode)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜