Are ints always initialized?

Is it possible to assume that int always initialized to 0 in Objective-C?

More specifically, when an object with int ivars was re-created, can it be assumed that its ivars has a value of 0?

+72
initialization objective-c int instance-variables
Jun 13 '09 at 14:58
source share
3 answers

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

The alloc method dynamically allocates memory for new instances of object instances and initializes them all 0-all, that is, with the exception of the isa variable, which binds the new instance to its class.




EDIT 2013-05-08
Apple seems to have deleted the above document (it is now associated with The Wayback Machine). In the currently active document, Objective-C Programming contains a similar link:

The alloc method has another important task, which is to clear the memory allocated for the properties of objects by setting them to zero. This avoids the usual problem with memory containing garbage from what was previously saved, but not enough to completely initialize the object.




However, this is true only for class variables; this is also true for POD types declared globally:

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

With one exception, this does not apply to local variables or to data allocated using malloc() or realloc() ; this is true for calloc() since calloc() explicitly discards the allocated memory.

The only exception is that when automatic reference counting (ARC) is enabled, stack pointers to Objective-C objects are implicitly initialized to nil ; however, it is still good practice to explicitly initialize them to nil . From Going to ARC Release Notes :

Stack variables are initialized with nil

Using ARC, strong, weak, and auto-implementing stack variables are now implicitly initialized with nil

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

+109
Jun 13 '09 at 15:03
source share

I do not think that you should accept any values ​​for initialization. If you build logic around the value "0", you must set it to be sure.

-one
Jun 13 '09 at 15:01
source share

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

-2
May 23 '13 at 15:58
source share



All Articles