'Why don't we use const char* const for constant strings? [closed]
The standard way to store a constant string in C++ is to use const char*.
In the interest of precision and correctness, why don't we write const char* const?
Is this just because people are too lazy to write the extra const, or because it really does have some disadvantage?
EDIT: I guess I should have been more clear, I don't need an explanation for what const does in it's various positions, I know that much already. What I wanted to know is why the convention is to write const char* even for variables where you know you are never going to change the pointer. Is it just a matter of taste and style?
Solution 1:[1]
const applies to the thing on its left, unless there is nothing there, then it applies to the thing on its right instead.
In const char * (which can also be written as char const *), the const is on the char, not on the *. So, this declares a mutable pointer to immutable const char data. Data cannot be modified through the pointer, but the pointer itself can be freely changed to point at any const char memory, eg:
const char *ptr = "string 1"; // OK
*ptr = 'S'; // illegal
ptr = "string 2"; // OK
In const char * const (which can also be written as char const * const), there is a const on the char, and there is a const on the *. So, this declares an immutable const pointer to immutable const char data. Data cannot be modified through the pointer, and the pointer itself cannot be changed once it has been initialized, eg:
const char * const ptr = "string 1"; // OK
*ptr = 'S'; // illegal
ptr = "string 2"; // illegal
And just for completeness, let's also consider char * const. The const is on the *, not on the char. So, this declares an immutable const pointer to mutable char data. Data can freely be modified through the pointer, but the pointer itself cannot be changed once it has been initialized, eg:
char buffer1[] = "string 1", buffer2[] = "string 2";
char * const ptr = buffer1; // OK
*ptr = 'S'; // OK
ptr = buffer2; // illegal
What I wanted to know is why the convention is to write
const char*even for variables where you know you are never going to change the pointer. Is it just a matter of taste and style?
Basically, yes. There is nothing stopping you from writing const char * const if you KNOW you are not going to change the pointer. It is just not a requirement, so it is very easy to omit the const on the pointer itself. What is more important is the type of data that the pointer is pointing at.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
