Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are pointers always set to nil on declaration?

Tags:

objective-c

I've found various people/articles (e.g. this SO answer) suggesting that the value of pointers in Objective-C is not defined until you assign something to it. However, I'm finding in practice that they are automatically set to nil even before I call alloc - the following code runs for me without asserting:

NSString* foo;          // 1
assert(foo==nil);       // foo is nil
foo = [NSString alloc]; // 2
assert(foo!=nil);       // after alloc, not nil.
foo = [foo init];       // 3
assert(foo!=nil);       // still not nil

Can/should I rely on this? Is it guaranteed or do I just happen to be running my compiler (Xcode) in some sort of debug mode? (I'm new to Objective-C).

A corollary question: what is the correct terminology to describe foo in the state at the end of the lines marked 1, 2 and 3? I imagine at least one of 1 & 2 them is termed 'uninitialised', and one of 2 & 3 is 'initialised', but which, and what do we call the third option?

like image 676
bacar Avatar asked Jan 30 '12 22:01

bacar


1 Answers

Under ARC, all object pointers are set to nil upon initialization. When not running under ARC, or when using pointers to other datatypes, an uninitialized pointer will have a garbage value (and in fact reading from the pointer produces undefined behavior according to the C standard).


@Chuck points out something important, which is that this only applies to local variables. Any variable with static storage (function statics, or globals) and instance variables are always initialized to their respective zero value (which, for pointers, is nil/NULL).

like image 128
Lily Ballard Avatar answered Oct 11 '22 23:10

Lily Ballard