📅 2011-Jul-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, initializer list ⬩ 📚 Archive
A common practice in C is to initialize the elements of arrays and structures to zero like this:
int iarr[3] = { 0 };
struct Foo foo = { 0 };
Experienced C programmers know that this kind of initialization works only for zero, not for any other value! 😊 For example, this will not initialize the elements of the array or structure to -1:
int iarr[3] = { -1 }; // Initialized to [-1, 0, 0]
struct Foo foo = { -1 };
The above only initializes the first element of the array or structure to -1. The rest are initialized to 0.
The single initializer shown in examples above is just a special case of an initializer list that does not completely handle all the elements of the array or structure. For such partial initializer lists, C will step in and initialize the rest of the elements to 0. For example:
int iarr[3] = { -1, 99 }; // Initialized to [-1, 99, 0]
Finally, modern compilers like Visual C++ provide an easier alternative to initialize all the elements to zero:
int iarr[3] = {}; // Initialized to [0, 0, 0]
For more on initializer lists, refer to Appendix A.8.7 in The C Programming Language (2nd Edition).