On initializing static variables
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!
January 4th, 2007 at 08:19:39
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
February 19th, 2007 at 14:45:21
That’s what I thought was standard for years, but got bitten on Intel lately. At least this switch helps.
March 23rd, 2010 at 14:43:53
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.