I know that for example "hello"
is of type const char*
. So my questions are:
-
How can we assign a literal string like
"hello"
to a non-const char*
like this:char* s = "hello"; // "hello" is type of const char* and s is char* // and we know that conversion from const char* to // char* is invalid
-
Is a literal string like
"hello"
, which will take memory in all my program, or it's just like temporary variable that will get destroyed when the statement ends?
Best Answer
In fact,
"hello"
is of typechar const[6]
.But the gist of the question is still right – why does C++ allow us to assign a read-only memory location to a non-
const
type?The only reason for this is backwards compatibility to old C code, which didn’t know
const
. If C++ had been strict here it would have broken a lot of existing code.That said, most compilers can be configured to warn about such code as deprecated, or even do so by default. Furthermore, C++11 disallows this altogether but compilers may not enforce it yet.
For Standerdese Fans:
[Ref 1]C++03 Standard: §4.2/2
C++11 simply removes the above quotation which implies that it is illegal code in C++11.
[Ref 2]C99 standard 6.4.5/5 "String Literals - Semantics":