0

In obj-c, do i have to initialise values eg pointers, or are they auto initialised to nil?

Eg:

- (void) myfunc {
    EpgSparseEntry *onNow=nil, *next=nil, *later=nil;
}

Do i need the =nil , or can i assume that variables on the stack are initialised to zero/nil?

Thanks

Chris
  • 39,719
  • 45
  • 189
  • 235

1 Answers1

2

Can i assume that variables on the stack are initialised to zero/nil?

No. Variables on the stack are not initialized so they contain random data.

That's different from an object's instance variables because all the memory an object occupies is zeroed out upon allocation.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
  • Useful to know that objects *are* zeroed out. – Chris May 06 '11 at 00:10
  • @Chris: I believe it's not part of the language spec so it should be considered an implementation detail on Apple's Obj-C platform. We can be pretty sure Apple won't ever change it, though. – Ole Begemann May 06 '11 at 00:12
  • I'm not sure there *is* a language spec. Apple's Obj-C implementation is effectively a de facto spec. But it's worth noting that `+[NSObject allocWithZone:]` does explicitly document this zeroing behavior, so you can rely upon it. – Lily Ballard May 06 '11 at 00:20
  • @Chris That’s not a feature of the language per se. However, it is a feature of `+[NSObject alloc]`, and it is documented behaviour. –  May 06 '11 at 00:21
  • Good point, Kevin. I suppose one could argue that `NSObject` is part of the framework, not the language, and Obj-C is one of the very few OO languages where object allocation and initialization are _not_ part of the language itself (`alloc`-`init` is defined in the Foundation framework, not the Obj-C runtime). Hence, the initialization of ivars cannot be part of the language spec. In practice, this makes absolutely no difference, though. – Ole Begemann May 06 '11 at 00:27