On initializing static variables

2007-01-04 00:23:20 UTC

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!

2 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.

    Daniel

  2. Patrick Stein Says:

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

Leave a Reply

Do not delete the second sentence.