variable, auto, static, register, volatile, type deduction
Storage 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++)
{
.
.
.
}
}
auto.
All variables defined in a function are auto or automatic by default, so in practice, programmers only use the keyword with type deduction. The scope of variables defined in a function is restricted to the local statements in the function, which explains why automatic variables are also called local variables. The program allocates memory for automatic or local variables when the variable comes into scope and deallocates it when it goes out of scope, making it difficult to see the distinction between the terms scope and memory allocation. The program explicitly initializes automatic variables (with the assignment operator) each time it calls the defining function.
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.
The program allocates memory for and initializes 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.
register.
Programmers use the register modifier to suggest that a program uses a variable often enough that keeping it in a CPU register, rather than memory, will improve efficiency. However, the number of available CPU registers is relatively small and varies by manufacturer and model, so the keyword was never more than a suggestion the compiler could ignore. Modern compilers incorporate register-optimization algorithms that generally outperform programmers at selecting the best variables to store in registers, so programmers rarely use this keyword today.
volatile.
Programmers denote variables subject to change by entities outside the program (e.g., sensors, communication links, etc.) with the volatile keyword, instructing the program to load the saved value from memory whenever it uses the variable. The compiler does not include volatile variables in its register optimizations. Only specialized programs use the volatile modifier.