Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning string literals to char*

Is the following code legal, deprecated or illegal in C++0x?

char* p = "foobar";

I originally asked this question here as a comment.

like image 661
fredoverflow Avatar asked Jun 27 '11 11:06

fredoverflow


People also ask

Can you assign a string literal to a char pointer?

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.

Is char * a string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars.

How do I store string in char pointer?

char *str = "GfG" ; In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in read-write memory. You can change str to point something else but cannot change value at present str.

What is char in string literal?

1) character string literal: The type of the literal is char[N], where N is the size of the string in code units of the execution narrow encoding, including the null terminator. Each char element in the array is initialized from the next character in s-char-sequence using the execution character set.


1 Answers

The conversion

char* p = "foobar";

is deprecated in C++98/C++03, and has been removed (that is, §4.2/2 removed) in C++0x.

So, the code is not valid in C++0x.

However, MinGW g++ 4.4.1 still only emits a warning, not error.

C++98/C++03 §4.2/2 (which is removed in C++0x):


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. ]
like image 151
Cheers and hth. - Alf Avatar answered Nov 07 '22 00:11

Cheers and hth. - Alf