3
    char s[10] = "Test";

How are the remaining chars (after "Test" and terminating null) initialized? (Is it defined?)

Background

I'm doing this to write a custom fixed-width (and ignored) header into an STL file. But I wouldn't like to have random/uninitialized bytes in the remaining space.

Museful
  • 6,711
  • 5
  • 42
  • 68

2 Answers2

2

The general rule for any array (or struct) where not all members are initialized explicitly, is that the remaining ones are initialized "as if they had static storage duration". Which means that they are set to zero.

So it will actually work just fine to write something weird like this: char s[10] = {'T','e','s','t'};. Since the remaining bytes are set to zero and the first of them will be treated as the null terminator.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • Is that equivalent to `char s[10] = "Test";`? – Museful Mar 26 '21 at 12:03
  • @Museful In this specific case, yes. But there are situations where it wouldn't be, see https://stackoverflow.com/questions/58526131/how-should-character-arrays-be-used-as-strings. – Lundin Mar 26 '21 at 12:08
2

How are the remaining chars (after "Test" and terminating null) initialized? (Is it defined?)

Yes, it's well defined, in a char array initialized with a string literal and with specified size larger than the length of the string literal all the remaining elements are zero-initialized.

From C++ standard (tip-of-trunk) Character arrays § 9.4.3 [dcl.init.string]

3. If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized ([dcl.init]).

Some examples from cppreference:

char a[] = "abc";
// equivalent to char a[4] = {'a', 'b', 'c', '\0'};

//  unsigned char b[3] = "abc"; // Error: initializer string too long
unsigned char b[5]{"abc"};
// equivalent to unsigned char b[5] = {'a', 'b', 'c', '\0', '\0'};

wchar_t c[] = {L"кошка"}; // optional braces
// equivalent to wchar_t c[6] = {L'к', L'о', L'ш', L'к', L'а', L'\0'};
anastaciu
  • 23,467
  • 7
  • 28
  • 53