Saturday, 23 November 2013

[C programming] Storage classes in C

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.

AutoRegisterStaticExtern
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 memoryStored in CPU registersStored in Data segmentStored 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 0Default initial value: Default initial value of variable is 0
Scope: local to the functionScope: local to the functionScope: local to the functionScope: 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 callsVariable can be shared between multiple files
Lifetime: Variable is de-allocated when the function (where the variable is declared) execution is overLifetime: Variable is de-allocated when the function execution is overLifetime: 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

You might also like

Related Posts Plugin for WordPress, Blogger...