2

Uninitilized Global int are always 0 as per defined beheviour, this is not true if it is not global. What about Global structs? Does

struct s
{
    int a;
}instance;

int main()
{    
    printf("%d\n", instance.a);
    return 0;
}

always print 0 or is it technically undefined beheviour?

FrostKiwi
  • 741
  • 1
  • 6
  • 16

1 Answers1

3

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thanks! Your excerpt explains it perfectly. I was a bit confused by the C99 passage often cited and CTRL+F through the C89 standard before to read __`If there are fewer initializers in a list than there are members of an aggregate, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. `__ just to be confused by the language and C99's usage of "brace-enclosed list" in the equivalent passage. – FrostKiwi Jul 25 '18 at 12:29