Home > Article > Backend Development > Why Choose `const char * const` over `const char *` in C ?
const char * const versus const char * in C
A common question arises when examining code utilizing constant character pointers: why use const char * const over const char *? Let's explore this using an example code:
<code class="cpp">void print_string(const char * the_string) { cout << the_string << endl; } int main () { print_string("What's up?"); }</code>
Here, two options arise for the parameter to print_string: const char * and const char * const. The distinction between them lies in their pointer mutability.
Why does both options work in practice? In the example, neither the string nor the pointer is modified in print_string. The relevance of const char * arises when attempting to change the pointed-to string.
Consider the following variations:
In the provided example, const char * const would be a more appropriate choice to prevent unintended modification of the_string within print_string. It serves as an additional safeguard against potential errors.
The above is the detailed content of Why Choose `const char * const` over `const char *` in C ?. For more information, please follow other related articles on the PHP Chinese website!