Partial Initialization of Automatic Structures and Arrays in C and C
The misconception stems from the incorrect assumption that partial initialization of automatic structures and arrays is allowed in C. Contrary to this belief, the standards explicitly define only two cases: complete initialization or no initialization.
Partial Initialization
The term "partial initialization" is not defined in the standards. It refers to initializing only a subset of members in a structure or array.
Complete Initialization
Complete initialization occurs when all members of a structure or array are explicitly initialized. For example:
struct somestruct { int a; int b; int c; }; somestruct s = {1, 2, 3};
No Initialization
When no initialization is provided, the behavior depends on the storage type of the variable:
Partial Initialization in Practice
Despite not being a standard behavior, partial initialization of automatic structure and array members is supported by most compilers, including Visual Studio and gcc/g .
C Standard (C99)
Section 6.7.8.21 Initialization
If fewer initializers are provided than the number of elements or members in an aggregate, the remaining elements are initialized to 0.
C Standard (C 03)
Section 8.5.1 Aggregates
If fewer initializers are present, the uninitialized members are value-initialized. Value initialization differs based on the object type. For example, non-static data members of a non-union class type are value-initialized, while primitive types like integers are zero-initialized.
Conclusion
Partial initialization of automatic structures and arrays is a non-standard behavior that may lead to undefined results if not handled properly. To ensure portability and correctness, always ensure complete initialization or no initialization.
The above is the detailed content of Is Partial Initialization of Automatic Structures and Arrays in C and C Allowed and Defined?. For more information, please follow other related articles on the PHP Chinese website!