const char * const versus const char *?
Mutable pointer to a mutable character
char *p;
Mutable pointer to a constant character
const char *p;
Constant pointer to a mutable character
char * const p;
Constant pointer to a constant character
const char * const p;
const char * const
means pointer as well as the data the pointer pointed to, are both const!
const char *
means only the data the pointer pointed to, is const. pointer itself however is not const.
Example.
const char *p = "Nawaz";
p[2] = 'S'; //error, changing the const data!
p="Sarfaraz"; //okay, changing the non-const pointer.
const char * const p = "Nawaz";
p[2] = 'S'; //error, changing the const data!
p="Sarfaraz"; //error, changing the const pointer.
The latter prevents you from modifying the_string
inside print_string
. It would actually be appropriate here, but perhaps the verbosity put off the developer.
char* the_string
: I can change which char
the_string
points to, and I can modify the char
to which it points.
const char* the_string
: I can change which char
the_string
points to, but I cannot modify the char
to which it points.
char* const the_string
: I cannot change which char
the_string
points to, but I can modify the char
to which it points.
const char* const the_string
: I cannot change which char
the_string
points to, nor can I modify the char
to which it points.