johnbakers
johnbakers

Reputation: 24770

Declaring variable above vs below @interface

int helloness;
@interface test : NSObject
@end

vs

 @interface test : NSObject{
int helloness;
}
@end

Do I understand that following are true and the only meaningful differences between the above two blocks:

In the first block, is this technically what is considered a "global variable" in that any class that imports this will have access to the same contents of helloness?

What happens if multiple header files have a declaration for helloness and you import them all?

Similar to this, consider this implementation:

 @implementation AClass

 int food=5;

Here, food acts like an internal iVar, even though it was not declared in any @interface ?

Upvotes: 2

Views: 220

Answers (2)

rickster
rickster

Reputation: 126137

In your first example, helloness is a global variable. It can be seen by any file which imports that header. If you include multiple headers which also declare an int helloness variable, I believe you'll get a warning from the compiler, and all of them will point at the same memory location. If you include another header which declares a helloness of type other than int, I believe you'll get a compiler error.

In the second example, helloness is an instance variable (ivar). Its value (memory location) is specific to each instance of AClass. (Anything can access it: e.g. AClass *instance = [[AClass alloc] init]; instance->helloness = 7; However, direct access to ivars is generally avoided in ObjC -- we use accessors and/or properties instead.)

In the third case, food is still a global variable, but its visibility is restricted to the implementation file it's declared in. Any instance of AClass, as well as any other classes or categories or functions implemented in the same file, can reference food, and all those references are to the same memory location.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224972

In your first example, helloness is a global variable. In your second example, it's an instance variable.

There can be only one global variable with a given name in your program. There is a copy of an instance variable for each instance of your class that's created during your program's execution. They're not semantically similar at all.

Having a global variable in a header file, as I presume you are doing in the first example since you refer to #importing it, is probably a bad idea. If it's not a tentative definition like yours is (for example if you instead had int helloness = 12;), you'll end up with multiply defined symbol errors at link time.

In your last example, food is still a global variable, but since it's likely to be in an implementation file (rather than a header), you probably won't run into any multiply defined symbol errors. It won't work like an instance variable, though - it's still a global variable.

Upvotes: 2

Related Questions