01 January 2005

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 Bohr is of type const 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 was char*. Allowing the assignment of a string literal to a char* 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