I have the following code
int t[] = {
[1] = 45,
[2] = 33
};
What will be the value of t[0]
in this case? It will contains garbage?
Uninitialized Array Elementsassigns a new value to the first element of the array. Recall that it is not possible to similarly modify an element of a string. creates a new loan array of size MAX_LOANS whose elements are uninitialized.
The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.
It is called uninitialized because it is not initialized. If there was a defined default value, it would be called default-initialized. To clear a position in an array you have to do exactly nothing.
The behaviour on reading uninitialised elements of an array is undefined. The compiler is allowed to do anything. (All the elements of a can be read due to the brace initialisation, although in C++ you can write int a[5] = {}; ).
The other value(s) will be initialized; from C11 standard, §6.7.9 Initialization, ¶19 and ¶21:
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.
151) Any initializer for the subobject which is overridden and so not used to initialize that subobject might not be evaluated at all.
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 uninitialized int
with static storage duration are implicity initialized to zero; same section, ¶10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
- if it has pointer type, it is initialized to a null pointer;
- if it has pointer type, it is initialized to a null pointer;
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
- if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
- if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
The behavior is the same in C89 and C99.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With