Converting a String Constant to a Char Pointer?
I was trying to learn some C++ but I don’t want to learn it like a brand new language, so I wanted to see how much of my C code could still work when compiled as C++, and to my surprise,
char *ptr = "str"; triggered a warning message.
warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
It really surprised me since this is almost the most ordinary C statement I can think about and I did not really understand the warning message. It’s only after I read this answer on StackOverflow that I can understand what happened. And here is what happened.
const int a = 1;
int *ptr = &a;
A string literal is a piece of unmodifiable data, just like
a, and when it appears to the right of an assignment operator, it behaves like a pointer to itself. If we assign such a pointer/address to a pointer that is not declared as a const (that is, not
const int *ptr = &a;), we can easily modify the value pointed at without notice, contradicting its constant nature. It doesn’t make much sense to write this way now that you know what’s going on and that’s why people say that the const keyword in C doesn’t really mean constant.
However, both C and C++ have been quite tolerant of this implicit conversion all the time, and it’s because the history of the language, dating back to those days when people did not have such thing as constant variables yet. As a result, many people today can be so used to this legacy “idiom” without noticing what’s actually going on under the hook, just like myself.