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
- Where to store the value of variable: registers of memory
- Specify the scope of the variable
- 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.
Let's take a look at an example of 'auto' storage class.
- #include <stdio.h>
- int main( )
- { //Code block 1
- auto int a = 1;
- { //Code block 2
- auto int a = 2;
- { //Code Block 3
- auto int a = 3;
- printf ( "\n Value of 'a' in Code Block 3: %d", a);
- }
- printf ( "\n Value of 'a' in Code Block 2: %d", a);
- }
- printf ( "\n Value of 'a' in Code Block 1: %d", a);
- }
- Output:
- Value of 'a' in Code Block 3: 3
- Value of 'a' in Code Block 2: 2
- 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.
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:
Post a Comment