What are static variables designed for? What's the difference between static int and int?
-
Possible Duplicate: http://stackoverflow.com/questions/1706675/file-scope-and-static-floats – sellibitze Oct 07 '10 at 18:02
3 Answers
The static
keyword has four separate uses, only two of which are closely related:
- static at global and namespace scope (applied to both variables and functions) means internal linkage
- this is replaced by unnamed namespaces and is unrelated to the rest
- in particular, others tend to imply some sort of uniqueness, but internal linkage means the opposite: you can have many objects with the same name, as long as each has internal linkage and you only have one per translation unit
- static data members are "shared" among all instances of the class
- it's more like they are independent of any class instance
- this is sometimes grouped with static methods
- static methods do not "operate" on a current instance
- no this pointer; can call without an instance
- static local variables (in functions) persist across the scope of each function call
Both static data members and static local variables can become hidden global state, and should be used carefully.
Now which two are closely related? It's not the two class members—the warning about global state gives it away. You can consider static data members as static local variables, where the functions to which they belong are all methods of the class, instead of a single function.
I found many related questions, but, surprisingly, no duplicates.

- 1
- 1
Static variables are initialized in the data segment (on x86; modify as appropriate for other architectures) instead of on the stack. They persist for the life of the program instead of vaporizing once they go out of scope.

- 776,304
- 153
- 1,341
- 1,358
-
It's not clear, but you seem to be mixing two different meanings of static into one definition. – Martin York Jan 03 '10 at 17:07
A static member can be referenced without an instance.
See the "Static Members" section here: http://www.cplusplus.com/doc/tutorial/classes2/

- 43,482
- 6
- 101
- 102
-
1The question, though, was about static variables, not members. – Michael Krelin - hacker Jan 03 '10 at 16:48
-
It's not clear the OP was making that distinction, even though 'variable' was the term used. – Jan 03 '10 at 17:08
-
@Michael: Which could mean static member variable (it depends what the original question is about and it is not 100% clear). – Martin York Jan 03 '10 at 17:09
-
Martin, yes, it could, but I'd want more evidence before narrowing it down. And just in case - if there were downvotes, then not mine - I only thought the answer deserves comment ;-) – Michael Krelin - hacker Jan 03 '10 at 19:24