What type of initialization is the following?
char a[] = ""; // ??? (copies array content)
char* q = a; // copy-initialization (copies pointer)
// EDIT: originally it was `char q[] = a;` which doesn't compile
In C, it's called "array initialization".
In C++, it looks like copy-initialization, but I'm not sure. What is the exact paragraph in the standard where it's named?
This is what the C++23 standard has to say about it:
An array of ordinary character type (6.8.2), char8_t
array, char16_t
array, char32_t
array, or wchar_t
array may be initialized by an ordinary string literal, UTF-8 string literal, UTF-16 string literal, UTF-32 string
literal, or wide string literal, respectively, or by an appropriately-typed string-literal enclosed in braces (5.13.5).
Additionally, an array of char
or unsigned char
may be initialized by a UTF-8 string literal, or by such a string literal enclosed in braces. Successive characters of the value of the string-literal initialize the elements
of the array, with an integral conversion (7.3.9) if necessary for the source and destination value.
[Example 1 :
char msg[] = "Syntax error on line %s\n";
shows a character array whose members are initialized with a string-literal. Note that because \n
is a single character and because a trailing \0
is appended, sizeof(msg)
is 25. — end example]
There shall not be more initializers than there are array elements.
[Example 2 :
char cv[4] = "asdf"; // error
is ill-formed since there is no space for the implied trailing \0
. — end example]
If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized (9.4).
The standard doesn't mention the initialization from string literals more specifically than: "string literals may initialize arrays of ..." and the corresponding CharT which means it falls back to a plain aggregate initialization.
My conclusion is debatable and I find it hard to say with certainty that it is correct. It could also be that it should be seen as a plain copy-initialization.
[dcl.init.general]
=
form of a brace-or-equal-initializer or condition (8.5), as well as in argument passing, function return, throwing an exception (14.2), handling an exception (14.4), and aggregate member initialization other than by a designated-initializer-clause (9.4.2), is called copy-initialization.