Sunday, 1 July 2012

Storage Class

Storage Class:

Every variable and function in C programming has two properties: type and storage class. Type refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:

  • automatic
  • external
  • static
  • register

Automatic storage class:

Keyword for automatic variable:

auto
 
 
Variables declared inside the function body are automatic by default. These variable are also known as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are rarely used.

External storage class:

External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.




Static Storage Class:

The value of static variable persists until the end of the program. A variable can be declared static using keyword: static. For example:

static int i;
 
 

Register Storage Class:

Keyword to declare register variable:

register
 
 
Example of register variable:

register int a;
 
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared register variables.
Since, there are limited number of register in processor and if it couldn't store the variable in register, it will automatically store it in memory.

 
 
 
 

No comments:

Post a Comment