views:

289

answers:

3
- (void)playAlarmSound:(NSTimer *)theTimer {
    static SystemSoundID soundID/* = 0 */; // ?
    if (!soundID) {
        soundID = [Utilities createSystemSoundIDFromFile:@"beep" ofType:@"caf"];
    }
    ...
}

Is SystemSoundID (which is a UInt32) automatically assigned 0? or should I explicitly assign it? I have to do it this way and test to see if it hasn't been initialized by the Utilities method because it doesn't compile if I just do static SystemSoundID soundID = [Utilities createSystemSoundIDFromFile:@"beep" ofType:@"caf"];. At first I tried assigning it to NULL, but then I realized its not a pointer, so anyway, should I have the = 0 in there or is it redundant?

+2  A: 

This doesn't have anything to do with the type — it has to do with storage class. In C, static and global variables are automatically initialized to 0. Ordinary local (auto) variables aren't automatically initialized, so you have to do it yourself or they'll contain garbage.

Chuck
+2  A: 

I believe objective-c follows the same rules as C for this.

static and global variables are initialized to 0 while local (i.e. auto) variables are not initialized and can start with an unpredictable value.

That said, it doesn't hurt to explicitly initialize the value to 0.

R Samuel Klatchko
+2  A: 

This question doesn't involve any objective-c features, so the answer is found in the c standard.

C99, section §6.7.8, paragraph 10:

If an object that has static storage duration is not initialized explicitly, then:

...

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

UInt32 (which itself is just uint32_t) is an arithmetic type. Hence, initialized to zero.

Stephen Canon