auto, static, extern, register, volatile, type deductionStorage modifiers are keywords that change a variable's primary or default behavior. C and C++ include four modifiers. Described previously, the auto and static keywords are included here for completeness.
void print(double p, double r, int n)
{
double total_interest = 0.0; // initialized on every function entry
double total_principal = 0.0;
for (int i = 1; i <= n; i++)
{
.
.
.
}
}
double random()
{
static double x = 0; // initialization happens once when the OS loads the program for execution
x = x * (x + 1) % 2147483648L;
return x;
}
static variables once at program startup. The memory remains allocated throughout program execution, "remembering" saved values between function calls. The program only deallocates the memory when it terminates.
| Global Variables | Pre-ANSI-C Functions | ||
|---|---|---|---|
| Definitions | Declarations | Definitions | Declarations |
char c; int x = 10; |
extern char c; extern int x; |
T0 function(p1, p2, p3)
T1 p1,
T2 p2
{ /* function body */ } |
extern T0 function(); |
| (a) | (b) | ||
extern keyword distinguishes between definitions and declarations. In the past, it provided essential behaviors for variables and functions in C programs, but its usefulness has declined in C++ and ANSI C.
extern keyword tells the compiler the variable is defined in an "external" file, distinguishing its definition from its declarations. Classes eliminate the need for global variables in most cases, reducing the use of extern in C++ programs.extern keyword to denote a declaration. Programmers can optionally initialize variables in definitions, but cannot initialize them in declarations. The figure uses Tn to denote various unspecified data types.