Search code examples
c++language-lawyerc++98

Initialize array based on C++ version and compiler


In C++11 or higher regardless of compiler int myArray[10] = { 0 }; would initialize to all elements to zero. The question is would this also work in C++98 and could the compiler not decide to initialize all elements to zero? In other words could C++98 with a given compiler ignore the assigning zero to all elements?

I found this page: https://en.cppreference.com/w/cpp/language/zero_initialization which lists C++98 defects about zero initialization.


Solution

  • All elements would be zero. Quotes from C++98:

    [dcl.init.aggr]

    If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized (8.5)


    [dcl.init]

    To default-initialize an object of type T means:

    • if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
    • if T is an array type, each element is default-initialized;
    • otherwise, the storage for the object is zero-initialized.

    The meaning of default initialisation was radically different in C++98 compared to its meaning starting from C++03 where the old default initialisation essentially was renamed value initialisation and the new default initialisation became to mean "no initialisation" for trivial types.

    Note that int myArray[10] = {}; would achieve the same goal. It's unnecessary to explicitly provide a value for the first element.