In: Computer Science
One of the following determines when the variable is created and destroyed and how long it will retain its value.
linkage |
||
storage class |
||
scope |
||
none of the above |
Answer :
storage class
Explanation :
The storage class of a variable determines its "lifetime", how long it remains in the computer's memory. Variables in C++ essentially fall into one of three storage classes:
Automatic storage Automatic variables are allocated and initialized automatically when program flow enters their scope, and de-allocated automatically when program flow leaves their scope. Automatic variables are stored on the program's call stack.
In C++, all local variables (including function and method parameters) are automatic variables by default.
Static storage Static variables are allocated and initialized once at the beginning of program execution. They continue to exist (and retain their value) throughout the execution of the program, regardless of whether or not they are currently in scope.
In C++, global variables are static variables by default. A
local variable or class data member (but not a function or method
parameter) may be made a static variable by placing the keyword
static
at the front of the variable declaration.
For example, in the following function the local variable
numCalls
is initialized to 0 at the start of the
program. It retains its value throughout the execution of the
program.
void countCalls() { static int numCalls = 0; // Value of numCalls is retained between each function call numCalls++; cout << "The countCalls function has been called " << numCalls << " times\n"; }
Dynamic storage Dynamic variables are allocated
at run time using the C++ operators new
and
new[]
. Dynamic variables exist until they are
explicitly de-allocated using the C++ operators delete
and delete[]
or the program ends. Dynamic variables
are allocated from a large pool of unused memory area called the
heap.