For example, if somestruct has three integer members, I had always thought that it was OK to do this in C (or C++) function:
somestruct s = {123,};
The first member would be initialized to 123 and the last two would be initialized to 0. I often do the same thing with automatic arrays, writing int arr[100] = {0,}; so that all integers in an array are initialized to zero.
Recently I read in the GNU C Reference Manual that:
If you do not initialize a structure variable, the effect depends on
whether it is has static storage (see Storage Class Specifiers) or
not. If it is, members with integral types are initialized with 0 and
pointer members are initialized to NULL; otherwise, the value of the
structure’s members is indeterminate.
Can someone please tell me what the C and C++ standards say regarding partial automatic structure and automatic array initialization? I do the above code in Visual Studio without a problem but I want to be compatible with gcc/g++, and maybe other compilers as well. Thanks
The linked gcc documentation does not talk of Partial Initialization it just talks of (Complete)Initialization or No Initialization.
The standards do not define Partial initialization of objects, either there is Complete initialization or No-initialization. Partial Initialization is a non-standard terminology which commonly refers a situation where you provide some initializers but not all i.e: Fewer initializers than the size of the array or the number of structure elements being initialized.
Example:
Initialization means providing some initial value to the variable being created at the same time when it is being created. ie: in the same code statement.
Example:
The quoted paragraph describes the behavior for
Case 3.The rules regarding Partial Initialization(
Case 1) are well defined by the standard and these rules do not depend on the storage type of the variable being initialized.AFAIK, All mainstream compilers have 100% compliance to these rules.
The C and C++ standards guarantee that even if an integer array is located on automatic storage and if there are fewer initializers in a brace-enclosed list then the uninitialized elements must be initialized to
0.C99 Standard 6.7.8.21
In C++ the rules are stated with a little difference.
C++03 Standard 8.5.1 Aggregates
Para 7:
While Value Initialization is defined in,
C++03 8.5 Initializers
Para 5: