Storage classes in C
C supports four different storage classes. These are auto,
register, static and extern storage classes.
C compiler automatically assigns auto storage class when we
declare a variable without any storage class.
<syntax of storage class in c>
<storage_class> <data_type> <variable_name>;
<storage_class> gives the information about where the
variable is stored in memory, default initial value, scope of the variable and
it’s life time.
Auto | Register | Static | Extern |
---|---|---|---|
Default storage class. int variable; /*Above Declaration is same as below one */ auto int variable; |
/*Declaration*/ register int variable; |
/*Declaration*/ static int variable; | /* Declaration */ extern int variable; |
Stored in stack memory | Stored in CPU registers | Stored in Data segment | Stored in Data segment |
Default initial value: Contains garbage value by default. | Default initial value: Contains garbage value by default. | Default initial value: Default initial value of variable is 0 | Default initial value: Default initial value of variable is 0 |
Scope: local to the function | Scope: local to the function | Scope: local to the function | Scope: visible to the outside of the file. |
Value of variable persists in function. | Value of variable persists in function. | Value of variable persists between function calls | Variable can be shared between multiple files |
Lifetime: Variable is de-allocated when the function (where the variable is declared) execution is over | Lifetime: Variable is de-allocated when the function execution is over | Lifetime: Variable is de-allocated when the program is terminated after completion of job. So, lifetime doesn’t dependent on function execution. | Lifetime: Variable is de-allocated when the program is terminated after completion of job. |
Extern variable vs Global variable:
The scope of the global variable is limited to the file
where it is declared. But, in case of extern variable, it can be shared among
functions. So, variable visibility is more compared to global variable.
Both global and extern variables are stored in data segment
and have default initial value is 0.
References:
No comments:
Post a Comment