C 使用未初始化的成员 int 定义的行为初始化全局结构?

C initilized global struct with uninitilized member ints defined beheviour?

根据定义的行为,未初始化的全局 int 始终为 0,如果它不是全局的,则不正确。全局结构呢? 有

struct s
{
    int a;
}instance;

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

总是打印 0 还是技术上未定义的行为?

对于全局结构,所有字段都将初始化为 0 / NULL。这在当前 C standard:

的第 6.7.9p10 节中有详细说明

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;

C89 standard在第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

因此在您的情况下,instance.a 保证设置为 0。