Why can a string literal be implicitly converted to char* only in certain case?

c, c++, implicit-conversion, string-literals, type-conversion

Solution

This behaviour differs between C and C++, at least in theory.

In C: a string literal decays to a non-const pointer. However, that doesn't make it a good idea; attempting to modify the string through that pointer leads to undefined behaviour.

In C++: it's never ok (AFAIK).* However, some compilers may still let you get away with it. GCC, for example, has the `-Wwrite-strings` flag, which is enabled by default (at least in 4.5.1 onwards).

* In C++11, at least. (I don't have older specs to hand.)

Problem

``` void f(char* p) {} int main() { f("Hello"); // OK auto p = "Hello"; f(p); // error C2664: 'void f(char *)' : cannot convert parameter 1 // from 'const char *' to 'char *' } ``` The code was compiled with VC++ Nov 2012 CTP. §2.14.15 String Literals, Section 7 A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration. Why is `f("Hello")` OK?

Original source

Related problems