3

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?

klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

4

In a word: efficiency.

For static objects, they have full program lifetime and so their initial values are set at compile time meaning there's no runtime cost. For automatic objects, they would need to be initialized every time they come into scope. So unless they are explicitly initialized it would be a waste of processor cycles to do so.

With regard to arrays as well as structs, an object is either initialized or it is not. So if at least part of it is explicitly initialized the rest has to be initialized as well. Presumably, this makes it easier for compilers to perform optimizations around uninitialized variables if it doesn't need to keep track of anything partially initialized.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Of course there is a run-time cost to initializing static objects. Setting memory to zero or other values is not free. It requires actual physical acton by the hardware. (Setting it to zero may have no **extra** cost if the operating system already does that for security/privacy protection, though.) – Eric Postpischil Oct 16 '19 at 02:46