Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Recently I came across the question NSString: Why use static over literal? and in the comments arrived a new question.

In Objective-C there some "special" types that are just maps to C primitives. Like the NSInteger.

typedef long NSInteger;
typedef int NSInteger;

I know how to use the static keywords for objects but I don't understand the implications on C primitive types.

When should I use a static NSInteger x instead of NSInteger x? What happens with the memory in both cases?

share|improve this question
Non-static variables are on the stack, static variables aren't. – rightfold Nov 25 '11 at 23:30
This question has been answered so many times on – user29079 Nov 28 '11 at 7:32
up vote 1 down vote accepted

The static key word can have three meanings as it related to primitives

  1. Declared inside a function. You could think of this as essentially creating a cache that only has scope in the function. The variable is only initialized once the first time the that function is called. The variable retains the same state it had from the previous call on all subsequent calls to the function. None static variables are put on the stack and have lifetime equivalent to duration of the function. The memory for static variables is someplace else and it always exists similarly to a global variable. In practice, I hardly see this used and personally, I don't think that I have ever used this outside of debugging.
  2. Declared in global scope. Using a static variable in global scope simply limits the scope of the variable to the file it was declared in. It is a global variable, but it is only accessible from the scope/file that it was declared in. I use this all the time. It is certainly good practice from a data encapsulation standpoint, but it also helps limit possible namespace collisions. There is no difference in memory usage.
  3. Declared in Class. This is similar to the first example. For each static variable in a class there is exactly one "copy" regardless of how many Class objects have been instantiated. It is sort of like a global variable that all instantiated objects of that type share.
share|improve this answer
I see the first case being used in UIKit to create new UITableViewCells to store the reuseIdentifier. – Felipe Cypriano Nov 30 '11 at 16:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.