- Scope of an object - gives information on visibility of a variable or function.
- Memory allocation - determines the part of memory where storage is allocated for an object and life of that object.
- auto
- extern
- static
- register
External variable - These variables are also called global variable. These variables remain in life throughout the execution of a program. Memory allocated for every byte of extern variable is initialized to zero. The keyword extern can be omitted for a variable that has scope of file. But it is must if the variable is used across several source files. So usually, deceleration and definition is associated with such variables.
Static variable/function - In case of variables, static defines lifetime but for functions it defines scope. As for extern/global variable, static variables are initialized to zero. Automatic initialization can be overridden explicitly by programmer. However, the initializer must be a constant expression. Static variable defined inside a program block has the same scope as that of automatic variable but the storage allocation remains in existence until program terminates.
Register variable - A programmer may instruct the compiler to allocate a register in CPU for a variable. However, a register variable may or may not be allocated CPU register at runtime. This keyword gives flexibility to a programmer to control the efficiency of a program to some extent. Generally, variables which are accessed repeatedly or whose access time are critical may be declared to be of storage class register. Interestingly, this is the only storage class that can be defined for function parameter.
Some interesting observation.
- A register variable must have to be defined within a block or it can also be declared as a function parameter.
- In C, pointers cannot reference a register variable. But this allowed in C++.
register int myVar = 0;int* myVarPtr = &myVar; /* NOT allowed */
- Register storage class can not be defined for a global variable.
- A register variable has the same life and scope as that of automatic variable.
- These are vaild.
register float myFlt; register char myChar; register int* myIntPtr; register double* myDobPtr; register float* myFltPtr; register char* myChrPtr;
- This is also valid.
int main(register int argc, char* argv[]) { .... .... return 0; }
How about these?
register int main(int argc, char* argv[]) { .... .... return 0; }
register int func1(int aa, char cc) { .... .... return 0; }
int func2(int aa, char cc) { static register int myInt = 0; .... return 0; }