Search code examples
c++initializationc++14

When a fixed-length char array is initialized with a short string, how is the remaining space initialized?


    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.


Solution

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