If struct a a1 = {0}; initializes all the elements (of different types) of a structure to zero, then struct a a2 = {5}; should initialize it to 5.. no?
#include <stdio.h>
typedef struct _a {
int i;
int j;
int k;
}a;
int main(void)
{
a a0;
a a1 = {0};
a a2 = {5};
printf("a0.i = %d \n", a0.i);
printf("a0.j = %d \n", a0.j);
printf("a0.k = %d \n", a0.k);
printf("a1.i = %d \n", a1.i);
printf("a1.j = %d \n", a1.j);
printf("a1.k = %d \n", a1.k);
printf("a2.i = %d \n", a2.i);
printf("a2.j = %d \n", a2.j);
printf("a2.k = %d \n", a2.k);
return 0;
}
The uninitialized struct contains garbage values
a0.i = 134513937
a0.j = 134513456
a0.k = 0
The initialized to 0 struct contains all elements initialized to 0
a1.i = 0
a1.j = 0
a1.k = 0
The initialized to 5 struct contains only the first element initialized to 5 and the rest of the elements initialized to 0.
a2.i = 5
a2.j = 0
a2.k = 0
Would a2.j and a2.k always guaranteed to initialize to 0 during a a2 = {5}; (or) is it an undefined behavior
OTOH, why am I not seeing all the elements of s2 initialized to 5. How is the struct initialization is done during {0} and how is it different when {5} is used?
Reference:
C99 Standard 6.7.8.21
[EDIT]
Static objects and implicit initialization:
The storage duration of an object determines the lifetime of an object.
There are 3 storage durations:
static, automatic, and allocated
variables declared outside of all blocks and those explicitly declared with the static storage class specifier have static storage duration. Static variables are initialized to zero by default by the compiler.
Consider the following program:
In the above program,
ihas automatic storage and since it is not explicitly initialized its value is Undefined.While
jhas static storage duration and it is guaranteed to be initialized to0by the compiler.