Defining pointers that point to string constants (aka string literals) as const char *
allows the compiler to detect an incorrect access if somewhere else in the code you try and modify what pt1
points to as in *pt1 = 'A';
whereas you would just have undefined behavior at runtime if pt1
had type char *
, causing a crash on some architectures and less obvious but potentially more damaging side effects on others.
To expand on this subject, there is sometimes a confusion as to the meaning of const
for pointer definitions:
const char *pt1 = "Hello";
defines a modifiable pointer pt1
that points to an array of char
that cannot be modified through it. Since "Hello"
is a string constant, it is the correct type for pt1
. pt1
can be modified to point to another string or char
, modifiable or not, or be set to NULL
.
char *pt2 = "Hello";
defines a modifiable pointer pt2
that points to an array of char
that can be modified through it. The C Standard allows this in spite of the constness of "Hello"
for compatibility with historical code. gcc and clang can disable this behavior with the -Wwrite-strings
command line option. I strongly recommend using this and many more warnings to avoid common mistakes.
const char * const pt3 = "Hello";
defines a constant pointer pt3
that points to an array of char
that cannot be modified through it. pt3
cannot be modified to point to another string or even be set to NULL
.
char * const pt4 = "Hello";
defines a constant pointer pt4
that points to an array of char
that can be modified through it. pt4
cannot be changed once initialized.
char
and const
can be placed in any order, but whether const
is before or after the *
makes a big difference.