Search code examples
objective-cinitializationprimitive

Do primitives need to be initialized to zero?


Do I need to explicitly zero primitives, i.e., set BOOLs to NO, set ints to 0?

Do I need to explicitly assign an NSString* to nil or @""?

I know that pointers must be explicitly set to nil, otherwise they may be filled with garbage. (Or is that only for Objective-C++?)


Solution

  • It depends on what kind of variable you're talking about. Globals, static variables and instance variables are already guaranteed to be initialized to 0.

    Local variables are a different story. They are never initialized at all by default, so you shouldn't read their values until you initialize or set them. It isn't strictly necessary to initialize them to 0 specifically. For example, the following code is very redundant:

    Controller *controller = nil;
    int countOfThings = 0;
    controller = [Controller sharedInstance];
    countOfThings = controller.totalThings - controller.thingsUsed;
    

    Instead, you should initialize variables to the values you actually want:

    Controller *controller = [Controller sharedInstance];
    int countOfThings = controller.totalThings - controller.thingsUsed;