tags:

views:

1365

answers:

3

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?

A: 

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
I assume we can see this as a valid answer for C++, while Adam's answer applies to Objective-C?
Felixyz
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
+24  A: 

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.

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).

Adam Rosenfield
Excellent! Many thanks!
Felixyz
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
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
A: 

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.

BjoernD