Is it safe to count on ints always being initialized to 0 in C?
More specifically, when an object with int ivars has been newly instantiated in Objective-C, is it safe to assume that those ivars have value 0?
Is it safe to count on ints always being initialized to 0 in C?
More specifically, when an object with int ivars has been newly instantiated in Objective-C, is it safe to assume that those ivars have value 0?
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.
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 theisa
variable that connects the new instance to its class.
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
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.
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).
While this may be true for Objective-C, it is definitely not true for C in general. For instance, a local variable in a function will not be initialized at all in C and therefore will contain an arbitrary value.