Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"hello world" string literal can be assigned to char * type?

char* foo = "fpp"; //compile in vs 2010 with no problem

I though string literal is const char* type.
And const type cannot be assigned to non-const type.
So I expect the code above to fail or am I missing something?

Edit: Sorry guys, I totally forgotten that compiler throws warning too.
I was looking at error list all this time.
I'm forget to check that.

Edit2: I set my project Warning Level to EnableAllWarnings (/Wall) and there's no warning about this.
So my question is still valid.

like image 831
kypronite Avatar asked Dec 04 '22 13:12

kypronite


1 Answers

C++03 deprecates[Ref 1] use of string literal without the const keyword.

[Ref 1]C++03 Standard: §4.2/2

A string literal (2.13.4) that is not a wide string literal can be converted to an rvalue of type “pointer to char”; a wide string literal can be converted to an rvalue of type “pointer to wchar_t”. In either case, the result is a pointer to the first element of the array. This conversion is considered only when there is an explicit appropriate pointer target type, and not when there is a general need to convert from an lvalue to an rvalue. [Note: this conversion is deprecated. See Annex D. ] For the purpose of ranking in overload resolution (13.3.3.1.1), this conversion is considered an array-to-pointer conversion followed by a qualification conversion (4.4). [Example: "abc" is converted to “pointer to const char” as an array-to-pointer conversion, and then to “pointer to char” as a qualification conversion. ]

C++11 simply removes the above quotation which implies that it is illegal code in C++11.

Prior to C++03, C++ derived its declaration of string literal without the const keyword, Note that the same is perfectly valid in C.

like image 51
Alok Save Avatar answered Jan 10 '23 23:01

Alok Save