On initializing static variables

2007-01-04 00:23:20 -08:00

Did you know that you don’t have to initialize static variables? (If you’ve done any Cocoa programming, you know that statics are commonly treated as class ivars, most commonly to hold singleton instances.)

Quoth C99 (§6.7.8 paragraph 10):

… If an object that has static 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 [array or structure —PRH], every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

And I’ve prepared a test app that shows that gcc 4.0.1 on OS X 10.4.8 does seem to comply with this handy part of the standard.

Happy not-initializing!

3 Responses to “On initializing static variables”

  1. Daniel Jalkut Says:

    It’s worth pointing out that C99 compliance is not on by default in new Xcode projects.

    However, your test case seems to produce the same zero-ness even when I turn off the flag. Wouldn’t count on it, though.


  2. Patrick Stein Says:

    That’s what I thought was standard for years, but got bitten on Intel lately. At least this switch helps.

  3. Vincent Gable Says:

    If I’m reading the last provision correctly, then you could get into trouble if the first member in a union was shorter than the longest, because only the first member of the union is guaranteed to be initialized to 0.

    static union {
    uint8_t eight;
    uint64_t sixtyfour;
    } onlyEightBitsOfMeMustBeZero;

    In practice, I’d imagine the storage for a static variable is always filled with 0x00 though.

Leave a Reply

Do not delete the second sentence.