Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 744
xmllmx Avatar asked Jan 19 '13 14:01

xmllmx


People also ask

Can string literals be assigned to char?

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 .

Is char * A string literal?

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.

Is it possible to modify a string literal?

The only difference is that you cannot modify string literals, whereas you can modify arrays.


2 Answers

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.)
like image 65
Oliver Charlesworth Avatar answered Oct 07 '22 05:10

Oliver Charlesworth


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.

like image 45
Cheers and hth. - Alf Avatar answered Oct 07 '22 05:10

Cheers and hth. - Alf