Describe about storage allocation and scope of global, extern, static, local and register variablesThe storage allocation / class determine the memory part where the storage space is allocated for variables, functions and how long the allocation of storage continues to exist.
The scope of a variable is specified by its storage allocation. This is specified by the keywords – auto, extern, static and register.
- ‘auto’ variables stores in the memory storage. Majority of the variables in a program / application are of type ‘auto’. Their scope might be local or global.
- ‘extern’ variables are of global variables and can be declared in another source file which could be external / outside the current program scope,
- ‘register’ variables are allocated in the CPU registers. These variables storage and accessibility is much faster than other variables, being they are stored in CPU itself. The variables of repeated usage or access time is critical, can be declared as register variables.
- ‘static’ variables provides a lifetime over the program, and provides a way for limiting the scope of such variables. These variables are automatically initialized to zero and could be specified for ‘auto’ and ‘extern’ variables. The values are retained, even though they are declared in local scope, between the repeated function calls to the same function.