views:

98

answers:

1

Is there any primitive data type that it's safe to not initialize?

How about structs like CGPoints or NSRects?

+3  A: 

It depends on where the variable is stored. The language specifies that all objects are zero'ed on alloc, which means all the ivars will be 0 filled. For any primitive type where the backing store being 0 makes sense then it is perfectly safe. For instance:

@interface LGDemo : NSObject {
  CGPoint point;
  NSRect rect;
}
@end

It is perfectly safe not to explicitly init point or rect, after the object is alloc'ed they will be {0.0, 0.0} and {0.0, 0.0, 0.0, 0.0} respectively.

Louis Gerbarg
what about local primitives? Which types are safe, none?
willc2
You mean on the stack? Stack variables are not guaranteed to be zero-filled, you need to initialize them manually.
Louis Gerbarg
Just to be clear, it is not about the types, it is about where they are stored. Type never has anything to do with it, except in as much as 0 backed memory may or may not be a sensical default value.
Louis Gerbarg
So ivars get created on the heap (always zero-filled) and locals are created on the stack (may be garbage), right? Note: I just started learning obj-c 4 months ago.
willc2
My mistake, it's been 6 months. Geez time sure flies...
willc2
That is basically correct. Technically heap allocation are not inherently zero filled (malloc'ed memory may have garbage just like the stack), but the runtime zeros any memory it gets from the heap before it hands it back to you.
Louis Gerbarg