Search code examples
c++arraysinitializationlanguage-lawyerstring-literals

What is the name of the initialization used in char a[] = ""?


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?


Solution

  • This is what the C++23 standard has to say about it:

    9.4.3 Character arrays [dcl.init.string]
    1. 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]

    2. 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]

    3. 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.

    9.4.2 Aggregates [dcl.init.aggr]
    1. An aggregate is an array or a class (Clause 11) with ...

    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.

    9.4.1. Initializers - General [dcl.init.general]
    1. The initialization that occurs in the = 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.