首页 > 解决方案 > Why are objects with automatic storage not zeroed when static objects are?

问题描述

In C, objects with automatic storage have an indeterminate value if they are not initialized, but static objects does not. From the 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;

We all know that C is a pretty unforgiving language that gives all the responsibility to the programmer, so it makes me wonder a bit why they decided to zero initialize static objects. I also wonder why automatic arrays are completely zero initialized if and only if at least one element is manually initialized. But what makes me most curious is why they did not choose to do this either for everything or nothing.

What is the rationale behind this?

标签: cinitializationstorage-duration

解决方案


一句话:效率

对于静态对象,它们具有完整的程序生命周期,因此它们的初始值是在编译时设置的,这意味着没有运行时成本。对于自动对象,每次进入范围时都需要对其进行初始化。因此,除非它们被显式初始化,否则这样做会浪费处理器周期。

关于数组和结构,一个对象要么被初始化,要么未被初始化。因此,如果它的至少一部分被显式初始化,其余的也必须被初始化。据推测,如果编译器不需要跟踪任何部分初始化的内容,这可能会使编译器更容易围绕未初始化的变量执行优化。


推荐阅读