| Lesson 7 || Storage classes |
| Objective || Examine the use of storage classes in C++. |
C++ - Storage Classes
Just as in C, C++ has four storage classes:
- automatic (keyword
- static, and .
- external (keyword
While the use of these storage classes remains largely the same as in C, it's worth taking a closer look at how C++ uses external and static declarations in multifile programs.
The ability to compile files separately is important when writing large programs. If we write a large program that is compiled as two separate files, then the use of an
extern variable in one file tells the compiler to expect
that the variable will be defined in the other file.
Static declarations allow a local variable to retain its previous value when the block is re-entered.
Another, more subtle use of
static is in connection with external declarations, with which it provides a privacy mechanism that is
very important for program modularity. By privacy, we mean visibility or scope restrictions on otherwise accessible variables or functions.
This use restricts the scope of the function.
Static functions are visible only within the file in which they are defined.
Unlike ordinary functions, which can be accessed from other files, a static function is available throughout its own file, but in no other. Again, this facility is useful in developing private modules of function definitions.