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"
.
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)
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.
String literals are stored in C as an array of chars, terminted by a null byte.
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.
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]:
Achar
array (whether plainchar
,signed char
, orunsigned char
) can be initialized by a string-literal (optionally enclosed in braces); awchar_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 (whetherplain char
,signed char
, orunsigned char
),char16_t
array,char32_t
array, orwchar_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.
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