According to N4606, 4.5 [conv.qual] paragraph 3 reads
A prvalue expression of type
T1
can be converted to typeT2
if the following conditions are satisfied, where cvij denotes the cv-qualifiers in the cv-qualification signature of Tj:
- ...
- If the cv1i and cv2i are different, then const is in every cv2k for 0 < k < i.
The final bullet above suggests that the following conversion fails.
T1 : pointer to / pointer to / pointer to / T
T2 : pointer to / pointer to / const pointer to / T
In order to succeed, T2
must be pointer to / const pointer to / const pointer to / T
. Isn't T2
sufficient just for being more cv-qualified than T1
? Why are more cv-qualifiers in lower dimensions necessary for the conversion to succeed?
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.
Simple: "char *name" name is a pointer to char, i.e. both can be change here. "const char *name" name is a pointer to const char i.e. pointer can change but not char.
1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
If you don't have the choice, using const char* gives a guarantee to the user that you won't change his data especially if it was a string literal where modifying one is undefined behavior. Show activity on this post. By using const you're promising your user that you won't change the string being passed in.
Consider the following code:
char str[] = "p1 should always point here.";
char* const p1 = str;
char** p2 = nullptr;
char*** p3 = &p2;
char str2[] = "Can we make p1 point to here?"
// p1 = str2; // does not work: const violation
// But:
char*const** p4=p3; // if it were allowed
*p4 = &p1; // no const violation, as *p4 is of type char*const*
**p3 = str2; // oops, changed p1!
So if the conversion in question were allowed, you'd get to change a constant variable (p1) without any formal const violation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With