23 June 2010

a note about storage classes in C

in C programming, there are number of storage classes and which is identifiers added to the start of the variable/function definition.

we will talk about some storage classes for variables which exactly: auto, static, register and extern.

The storage class identify two important aspects, the life time of the variable (a.k.a storage duration) and the scope of the variable.

1- auto:
auto is the default for locale variables (including function parameters).
life time: created when reached, destroyed at end of the block/function in which it is defined.
scope: to the closing brace "}" of the block/function in which it is defined unless it is override by variables with the same name in inner blocks.

2- static:
static is the default for global variables.
can also applied to local variables.
It makes the variable available once it is defined to end of the program (file? I am not sure)
default value is 0 and NULL for pointers.

life time:
for global and local variables, as long as the program is running.
scope:
for global variables: the whole file.
for local variables: the whole function in which it is defined (as auto variables)

the difference between static local variable and automatic local variable is that, the local created each time it is reached, but static is still in the memory with the last value.

note: global variables cannot defined as `auto`

extern:
my info about extern is just it is used by the linker to refer to another variable defined in some other files. and it is used by global variables only.

so, global variables can be either static or extern.

register:
instruct the compiler to save this variable in CPU registers instead of memory. (only suggest, not an obligation)

summary:
the most frequently used are auto (default for local variables) and static (default for global variables).
static variables are initialized by default to zero and NULL for pointers.
static variables retain its value as long as the program is running.
Post a Comment