76

Is it safe to count on ints always being initialized to 0 in Objective-C?

More specifically, when an object with int ivars has been newly instantiated, is it safe to assume that its ivars have value 0?

jscs
  • 63,694
  • 13
  • 151
  • 195
Felixyz
  • 19,053
  • 14
  • 65
  • 60

3 Answers3

119

Yes, class instance variables are always initialized to 0 (or nil, NULL, or false, depending on the exact data type). See the Objective-C 2.0 Programming Language:

The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the isa variable that connects the new instance to its class.


EDIT 2013-05-08
Apple seems to have removed the above document (now linked to The Wayback Machine). The (currently) active document Programming With Objective-C contains a similar citation:

The alloc method has one other important task, which is to clear out the memory allocated for the object’s properties by setting them to zero. This avoids the usual problem of memory containing garbage from whatever was stored before, but is not enough to initialize an object completely.


However, this is only true for instance variables of a class; it is also true for POD types declared at global scope:

// At global scope
int a_global_var;  // guaranteed to be 0
NSString *a_global_string;  // guaranteed to be nil

With one exception, it is not true for local variables, or for data allocated with malloc() or realloc(); it is true for calloc(), since calloc() explicitly zeros out the memory it allocates.

The one exception is that when Automatic Reference Counting (ARC) is enabled, stack pointers to Objective-C objects are implicitly initialized to nil; however, it's still good practice to explicitly initialize them to nil. From the Transitioning to to ARC Release Notes:

Stack Variables Are Initialized with nil

Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil

In C++ (and C++ objects being used in Objective-C++), class instance variables are also not zero-initialized. You must explicitly initialize them in your constructor(s).

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 3
    Spot on. However, the fact that people often wonder about this detail can be reason enough to be more explicit about initializing variables, arguably the "safer" choice. Initializing to 0/nil/NULL never hurt anyone... :-) – Quinn Taylor Jun 13 '09 at 16:36
  • I agree with Quinn. In this case, however, I'm creating an "abstract" class which doesn't implement -(void)init, and I don't want to force every subclass to remember to initialize the ivars. So it's good to know that I can count on them being initialized to 0. – Felixyz Jun 13 '09 at 18:06
  • My experience even in release mode for iOS is that even local variables are initialized to 0 – jjxtra Mar 24 '11 at 22:09
  • 4
    @PsychoDad My experience is the opposite. – titaniumdecoy May 10 '12 at 04:59
  • @AdamRosenfield Link to official doc is dead. Can you fix that? – Pang May 08 '13 at 00:56
  • 1
    @Pang: Fixed now. Apple has sadly removed the original "Objective-C 2.0 Programming Language" document AFAICT. – Adam Rosenfield May 08 '13 at 05:36
  • 1
    Under ARC local variables of type `id` are also initialized to nil. – CodeSmile Oct 25 '13 at 20:10
  • @LearnCocos2D: Do you have a citation/reference for that? – Adam Rosenfield Oct 26 '13 at 23:49
  • Apple ARC Release Notes, under Lifetime Qualifiers, subheading: stack variables are initialized with nil - https://developer.apple.com/library/ios/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW4 – CodeSmile Oct 27 '13 at 01:05
  • Does the same apply to `NSUInteger`s / `CGFloat`s ? – n00bProgrammer Dec 25 '14 at 13:10
  • 1
    @n00bProgrammer: Yes. In the situations described above, all variables are "zero-initialized" in whatever manner that means for their respective data types. Arithmetic types (`int`, `NSUInteger`, `CGFloat`, `float`, `bool`, `BOOL`, `char`, etc.) are all initialized to 0 represented in those types. – Adam Rosenfield Dec 25 '14 at 19:55
-1

I don't think you should assume any values for initialization. If you are building logic around a "0" value, you should set it to be sure.

Cody C
  • 4,757
  • 3
  • 29
  • 36
  • I assume we can see this as a valid answer for C++, while Adam's answer applies to Objective-C? – Felixyz Jun 13 '09 at 15:41
  • 11
    Adam's answer for Objective C is exactly right - Objective C absolutely guarentees that ivars are set to nil/NULL/false/0 on allocation and it is perfectly sensible to accept and use this fact. For example, this enables trivial lazy initialization of NSMultableArray* ivars with [NSMultableArray array or new] when they are noticed to be nil. Combined with Objective C guarentteing [(NSMultableArray*) count] returns 0, you can often defer the initialization even further. Learn to love the way Objective C does it, not just fight against its differences. – Peter N Lewis Jun 15 '09 at 01:52
-3

Yes, in C global vars are initialized to zero. In Objective-C even local vars are initialized to zero. You can count on it.

Tom01
  • 7
  • 1
    @AdamRosenfield's answer directly contradicts your claim that even local vars are initialized to zero. Who is wrong? – Mark Amery Aug 09 '13 at 15:05