The Static Keyword in C
The static keyword can be confusing in part because C reuses the same keyword to do different things. To understand it, we must understand the following <insert a noun you find appropriate here>:
- Each object have two main attributes, a storage class and a type.
- Storage class, either automatic (dynamic) or static, is about lifetime.
- Each name that refers to an object has a scope.
- Scope, either extern or static, is about linkage, i.e. its visibility to other files.
- Most of the time, you don’t need to explicitly specify the storage class of a variable or the scope of a name
- An object declared outside all blocks is always static and the objects declared inside a block are always automatic unless explicitly specified as static.
- A name outside all blocks is extern by default, that is, it will be visible to all other files by default and only following declarations require an extern keyword.
- Each name that refers to a static object can have an internal linkage by use of the static keyword.
Conclusions: You will never need the auto keyword, and most of the time you will not need the extern keyword either. The problem now becomes when and how you should use the static keyword. You will need a static keyword only when a) you define a variable inside a block, which is automatic by default, but you want it to last till the end of the program, or b) you define a variable outside all blocks but you don’t want other files to use it.