In fact these three code snippet
char *p="Hello"; /*pointer is variable,so string is*/
*p='M';
p="BYE"; /*works*/
p="Bye"; /*works*/
const char *q="Hello"; /*string is constant pointer is not */
*q='M'; /*Error*/
q="BYE"; /*works*/
char const *s="Hello"; /*string is constant pointer is not */
*s='M'; /*Error*/
s="BYE"; /*works*/
are equivalent in the sense that you may not change the object pointed to by the pointers. The difference is that adding qualifier const to definition of q allows the compiler to find the error at compile time.
You may not modify string literals. Any attempt to modify a string literal results in undefined behaviour of the program. In C string literals have type of non-const character arrays. However adding qualifier const as it is done in the second code snippet allows the compiler to find the error at compile time.
The C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
There is no difference except aesthetic between records
const char *
and
char const *
The both define pointers to constant objects. The pointers themselves are not constant.
However if you would write the following way
char s[] ="Hello"; /*pointer is variable,so string is*/
char *p = s;
const char *q = s;
*p='M';
*q='M';
then there is a difference between using pointers with or without const qualifier because you may change the character array. For the last statement the compiler will issue an error.
The last two code snippets differ from the first three code snippet in that the last two define constant pointers that is the value of pointers may not be changed. And then you are trying to reassign a constant pointer the compiler issues an error. Constant object shall be initialized when they are defined.