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?
String literals are usually referred to by a pointer to (or array of) characters. Ideally, they should be assigned only to pointers to (or arrays of) const char or const wchar_t .
char *amessage = "This is a string literal."; All escape codes listed in the Escape Sequences table are valid in string literals. To represent a double quotation mark in a string literal, use the escape sequence \". The single quotation mark (') can be represented without an escape sequence.
The only difference is that you cannot modify string literals, whereas you can modify arrays.
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).
The difference between
f("Hello");
and
f(p);
is that the former involves a literal. In C++03 conversion from string literal to char*
(note: not const
) was supported. It isn't supported any longer in C++11, but few if any compilers have yet caught up with that rule change.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With