An uninitialized global variable of type int always has a value of 0, as per C Standard.
This is not true if the variable is not a global, but what about global structs?
In the following example:
struct s
{
int a;
}instance;
int main()
{
printf("%d\n", instance.a);
return 0;
}
Would the program always print 0
or is it technically undefined behaviour?
For a global struct, all fields will be initialized to 0 / NULL. This is detailed in section 6.7.9p10 of the current C standard:
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 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 old C89 standard has similar language in section 3.5.7:
an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant. If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate
...
If the aggregate contains members that are aggregates or unions, or if the first member of a union is an aggregate or union, the rules apply recursively to the subaggregates or contained unions
So in your case, instance.a
is guaranteed to be set to 0.