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

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

What is the difference between the two ...

EDIT

by bjarne stroustrup 3rd edition p. 90

 void f() { char* p="plato"; p[4]='e' // error: assign to const;result is undefined } 

this type of error cannot be a common b, caught until the execution and implementation times differ from the application of this rule.

Same with const char * p = "plato"

That is why I am asking about the difference ... What does const matter here.

+1
source share
5 answers

The const char* option is correct.

You should not modify the memory that comes from a string literal (usually called static storage). This is read only memory.

The difference is that the char* option will allow you to write syntax to change the data it points to by dereferencing it. Actually this is what is undefined.

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

I would prefer option 2 with me.

+7
source

Declaring const char * p means that thing p points to const, i.e. should not change. I say should not, because you can drop the constellation. As mentioned, changing a string literal is undefined and often leads to an access violation / segmentation error.

Not this declaration is different from char * const p, which means that p is its const itself, and not the thing p points to.

0
source

The problem that Stroustrup is talking about is what you are quoting is that in C ++ a string literal will be easily converted to a "rvlaue of type" to char pointer (4.2 / 2 "Converting an array to a pointer") This is especially important, since the very common idiom of pointing a char* string to a literal string will not lead to a failure in compiling bazillion programs (especially when C ++ originally evolved from C).

If you can get away with declaring the pointer as char const* (or equivalent const char* ), you can help yourself deal with problems like those described in the Stroustrup quote. However, you may run into annoying problems using a pointer with functions that are not 100% matched.

0
source

See this question .

Basically,

 char *p="orkut"; 

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

0
source

note that more recent gcc implementations will not let you do

  char *foo = "foo"; 

they insist on const (of course in -wall -werror mode)

0
source

All Articles