Type of String Literals
I had always thought that the type of string literal, i.e. a string enclosed by
a pair of double quotes, was const char*. But, recently, I noticed a "weird"
thing: why the following line compiles successfully?
char* p = "this is weird";
We cannot assign const T[] to T* as that removes the const modifer.
Similar, string literals shall not be assigned to char *. At first, I
suspected it was a bug of compiler. But, changing an other copmiler still get
the same result. That really confused me until I happened to read the following
lines in The C++ Programming Language (special edition,5.2.2 String Literals):
The type of a string literal is "array of the appropriate number of const characters", so
Bohris of typeconst char[5].…
A string literal can be assigned to a
char*. This is allowed because in previous definitions of C and C++ , the type of a string literal waschar*. Allowing the assignment of a string literal to achar*ensures that millions of lines of C and C++ remain valid. It is, however, an error to try to modify a string literal through such a pointer;
blog comments powered by Disqus