Variable in C differ in behaviour from those in most other language.In C not do all variable have a data-type,they also have a storage class.The following variable storage classes are most relevant to function:-
- Local Variable
- Global Variable
- Static Variable
- Register variable
In this tutorial, We discuss the scope and visibility of each of the above class variables.
The Scope of the variable determines over what region of the program a variable is available for use while visibility refers to accessibility of a variable from the memory. It is very important to understand the concept of storage classes and their utility in order to develop the efficient multifunction program.
Automatic (Local) Variable
C Code Example
1 2 3 4 5 6 7 |
#include <stdio.h> void main() { /* local variable declaration */ int a = 2; printf ("value of a = %d",a); } |
These are declared inside a function in which they are to be utilized. They are created when the function is called and destroying automatically when the function is exited, hence the name is automatic(Local). This assure that we may use declare and use the same variable name in different functions in the same program without causing any problem to the compiler.
1 2 3 4 5 6 |
main() { data_type Variable_name; ----------- ----------- } |
We may also use Keyword auto to declare Local variable:-
1 2 3 4 5 6 |
main() { auto data_type Variable_name; ----------- ----------- } |
External(Global) Variable
C Code Example
1 2 3 4 5 6 7 8 |
#include <stdio.h> /* global variable declaration */ int a = 2; void main () { printf ("value of a = %d",a); } |
These variables can be accessed by any function in the program. These are active in the entire program thats why it is known as External or global variables. These are declared outside a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
data_type Variable_name; main() { ----------- ----------- } function_name() { ----------- ----------- } |
Static Variable
The value of the static variable persists until the end of the program. A variable can be declared static using the keyword static. A general form is:-
static data_type variable_name;
Register Variable
We can tell the compiler that a variable should be kept in one of the machines registers, instead of keeping the memory. Since register access is much faster as compared to memory access. keeping the frequently accessed variable(for example-loop control variable)in the register. A general form is:-
register data_type variable_name;
Since only a few variables can be placed in the register, it is important to carefully select the variable for this purpose. However,C will automatically convert the register variable into a non-register variable once the limit is reached.