Why is this array having all remaining values initialized to zero?

岁酱吖の 提交于 2019-11-27 09:46:30

C11 6.7.9 Initialization p19 covers this (my emphasis)

The initialization shall occur in initializer list order, each initializer provided for a particular subobject overriding any previously listed initializer for the same subobject;151) all subobjects that are not initialized explicitly shall be initialized implicitly the same as objects that have static storage duration.

Section 6.7.9 p10 states that

If an object that has static or thread storage duration is not initialized explicitly, then...if it has arithmetic type, it is initialized to (positive or unsigned) zero;

The C99 draft says:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

And static objects are initialized to zero.

So, there's a large difference between not having any initializer at all, that gives you the uninitialized contents of memory (what you call "garbage"), and having an initializer. If the initializer is there, but missing data, you get 0 by default.

This is very handy, since it makes it possible to 0-initialize a large array by doing just as you did.

The bit you are missing is that if you initialize just one element of an array, the rest of its elements will be automatically initialized to 0. The language is defined in this way.

Stefano Falasca

from the C standard as cited here (hit the link, you can find some more useful info there)

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!