Sunday, April 3, 2016

C Storage Class Specifiers - auto, register, static and extern

We know that, a specific number of bytes of space is required to store a value of a variable as needed by the type of variable. For example, 'char' requires 1 byte, 'int' requires 2/4 byte and so on. This space can be allocated from the memory of the system or from processor registers. Register access is always faster than memory access. What if we can specify to the compiler about where to store the variable? Also, how long to keep the value of variable in memory, it's initial value etc? Storage class specifiers are used for that purpose. Using storage class specifiers we can specify
  1. Where to store the value of variable: registers of memory
  2. Specify the scope of the variable
  3. Specify life time of variable
Storage class specifiers available in C programming language include 'auto', 'register', 'static' and 'extern'.

'Auto' Storage Class Specifier

A variable declared as 'auto' qualifier implies that the variable exists/accessible only with in the code block they are declared. For all the code blocks outside the declared code block, it's as if the variable doesn't exist. If some code outside of the code block tries to access an 'auto' variable, it will cause compilation error. By default, all variables are of auto storage class.

Let's take a look at an example of 'auto' storage class.
  1. #include <stdio.h>
  2. int main( )
  3. { //Code block 1
  4.  
  5. auto int a = 1;
  6. { //Code block 2
  7.  
  8. auto int a = 2;
  9. { //Code Block 3
  10.  
  11. auto int a = 3;
  12. printf ( "\n Value of 'a' in Code Block 3: %d", a);
  13. }
  14. printf ( "\n Value of 'a' in Code Block 2: %d", a);
  15. }
  16. printf ( "\n Value of 'a' in Code Block 1: %d", a);
  17. }
  18.  
  19. Output:
  20. Value of 'a' in Code Block 3: 3
  21. Value of 'a' in Code Block 2: 2
  22. Value of 'a' in Code Block 1: 1
From the above example, you can see that value of variable 'a' is different in each code block because they are declared as 'auto' and has scope only with in the declared block. The behaviour would be same even if you remove the 'auto' keyword from the variable declaration, because by default all variables are of type 'auto'.

Life of 'auto' variable is within the declared code block, they will cease to exist after the execution of corresponding code block and the initial value of variable would be garbage. So they need to be initialized with proper value before usage.

No comments: