Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an initialiser containing a string literal valid to initialise a `char` array?

Tags:

c++

It turns out that char c[] = {"a"}; is completely valid in both C++03 and C++11.

I would not expect it to be, because it is an array of char not of char const*, and I would expect a brace-initialiser to require a compatible type for each of its "items". It has one item, and that's a char const* not a char.

So what makes this initialisation valid? And is there a rationale for it being so?


Similarly, char c[] = {"aa"}; compiles, and printing c results in the output "aa".

I would expect char c[]{"a"} to be valid in C++11, of course, but it's not the same! Similarly, char c[] = {'a'} is obvious in both, as is char c[] = "a".

like image 819
Lightness Races in Orbit Avatar asked Nov 09 '11 11:11

Lightness Races in Orbit


People also ask

Which of the following is the correct way of initializing a character array?

Initialization of character arrays You can initialize a one-dimensional character array by specifying: A brace-enclosed comma-separated list of constants, each of which can be contained in a character. A string constant (braces surrounding the constant are optional)

How do you initialize a char array in C++?

In C++, when you initialize character arrays, a trailing '\0' (zero of type char) is appended to the string initializer. You cannot initialize a character array with more initializers than there are array elements. In ISO C, space for the trailing '\0' can be omitted in this type of information.

Are string literals arrays?

String literals are stored in C as an array of chars, terminted by a null byte.

What is the difference between character array and string literal?

String refers to a sequence of characters represented as a single data type. Character Array is a sequential collection of data type char. Strings are immutable.


1 Answers

Although it may not necessarily be intuitive, it simply is allowed; there's a distinct rule for it in both standards:

[2003: 8.5.2/1]: A char array (whether plain char, signed char, or unsigned char) can be initialized by a string-literal (optionally enclosed in braces); a wchar_t array can be initialized by a wide string-literal (optionally enclosed in braces); successive characters of the string-literal initialize the members of the array. [..]

[n3290: 8.5.2/1]: A char array (whether plain char, signed char, or unsigned char), char16_t array, char32_t array, or wchar_t array can be initialized by a narrow character literal, char16_t string literal, char32_t string literal, or wide string literal, respectively, or by an appropriately-typed string literal enclosed in braces. Successive characters of the value of the string literal initialize the elements of the array.

I can't explain why the committee made it this way, though.

like image 112
Lightness Races in Orbit Avatar answered Oct 07 '22 01:10

Lightness Races in Orbit