There is more than one way to declare pointers with the same const
, qualification, and this can make reading and writing pointer declarations difficult. For example, what does this mean?
char * const cp;
A simple rule I find useful is this:
Split the expression on the asterisks. If the word
const
is on the left, then it refers to the pointed-to value. If it’s on the right, then it refers to the pointer.
So looking at our example, the const
is on the right of the asterisk, so it is the pointer that is const
.
Below are examples of all of the const expression types for a single pointer, showing which assignments are possible. Notice that assigning a string literal to a pointer to non-const
produces a warning, while assigning it to a pointer to const
does not.
char *cp0 = "cp0"; // warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] const char *cp1 = "cp1"; // OK cp1[0] = 'f'; // error: assignment of read-only location ‘* cp1’ cp1 = NULL; // OK char * const cp2 = "cp2"; // warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] cp2[0] = 'f'; // OK cp2 = NULL; // error: assignment of read-only variable ‘cp2’ const char *const cp3 = "cp3"; // OK cp3[0] = 'f'; // error: assignment of read-only location ‘*(const char*)"cp3"’ cp3 = NULL; // error: assignment of read-only variable ‘cp3’ char const *cp4; // OK, same as cp1 cp4[0] = 'f'; // error: assignment of read-only location ‘* cp4’ cp4 = NULL; // OK