pict pict - 3 months ago 46
C Question

const char * const versus const char *?

I'm running through some example programs to refamiliarize myself with C++ and I have run into the following question. First, here is the example code:

void print_string(const char * the_string)
{
cout << the_string << endl;
}

int main () {
print_string("What's up?");
}


In the above code, the parameter to print_string could have instead been
const char * const the_string
. Which would be more correct for this?

I understand that the difference is that one is a pointer to a constant character, while one is a constant pointer to a constant character. But why do both of these work? When would it be relevant?

Answer

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 the char to which the_string points, and I can modify the char at which it points.

const char* the_string : I can change the char to which the_string points, but I cannot modify the char at which it points.

char* const the_string : I cannot change the char to which the_string points, but I can modify the char at which it points.

const char* const the_string : I cannot change the char to which the_string points, nor can I modify the char at which it points.