The Storage Class Specifiers

The type modifiers extern, auto, register, static, and mutable are used to alter the way C/C++ creates storage for variables. These specifiers precede the type that they modify.

extern

If the extern modifier is placed before a variable name, the compiler will know that the variable has external linkage. External linkage means that an object is visible outside its own file. In essence, extern tells the compiler the type of a variable without actually allocating storage for it. The extern modifier is most commonly used when there are two or more files sharing the same global variables.

auto

auto tells the compiler that the local variable it precedes is created upon entry into a block and destroyed upon exit from a block. Since all variables defined inside a function are auto by default, the auto keyword is seldom (if ever) used.

register

When C was first invented, the register modifier could be used only on local integer, character, or pointer variables because it caused the compiler to attempt to keep that variable in a register of the CPU instead of placing it in memory. This made all references to that variable extremely fast. The definition of register has since been expanded. Now, any variable may be specified as register and it is the compiler’s job to optimize accesses to it. For characters, integers, and pointers, this still means putting them into a register in the CPU, but for other types of data, it may mean using cache memory, for example. Keep in mind that register is only a request. The compiler is free to ignore it. The reason for this is that only so many variables can be optimized for speed. When this limit is exceeded, the compiler will simply ignore further register requests.

static

The static modifier instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable’s scope to be restricted to the file in which it is declared. This means that it will have internal linkage. Internal linkage means that an identifier is known only within its own file.

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

mutable

The mutable specifier applies to C++ only. It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net