js_
js_

Reputation: 4731

in Objective-c, if structure is not initialized, what value does its member return?

I want to know height of a view.

NSInteger height = view.frame.size.height;

In above code, frame and size are structure and view is object.
If view is nil in the above code, what value does height return?

I know that I get nil if I send message to nil object.
But size is not object.

When I ran the above code, I get 0 if view is nil.
Does it always return 0, or returning 0 isn't guaranteed?

Also in the following code, height returns zero.

CGSize size;
NSInteger height = size.height;

In Objective-C, structures which are not initialized always returns zero?

Upvotes: 3

Views: 1202

Answers (2)

rob mayoff
rob mayoff

Reputation: 385680

In your first example (view.frame.size.height), you are guaranteed to get 0 if view is nil. This became true in Xcode 4.2 (using clang); for older compiler versions (and gcc I believe) the result is undefined. Source: Greg Parker's blog.

For your second example, it depends on where CGSize size; is declared. If it's a local variable like this:

- (void)someMethod {
    CGSize size;
    NSInteger height = size.height;
    ...
}

then height is undefined. It might be zero, or it might be any other number.

If it's an instance variable like this:

@implementation MyObject {
    CGSize size;
}

then it is guaranteed to be initialized to zero by +[MyObject alloc].

If it's a global variable like this:

// outside of any method, function, or class variable section
CGSize size;

(or a static variable) then it's guaranteed to be initialized to zero when your app launches.

Upvotes: 7

user529758
user529758

Reputation:

It's not a structure that is not initialized. In fact, it's initialized to all zeroes by objc_msgSend_stret() exactly for this reason: structure returning messages sent to nil return 0 for all members.

Upvotes: 2

Related Questions