A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
There are following storage classes which can be used in a C Program
- auto
- register
- static
- extern
auto - Storage Class
auto is the default storage class for all local variables.
{
int Count;
auto int Month;
}
|
The example above defines two variables with the same storage class. auto can only be used within functions, i.e. local variables.
register - Storage Class
register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&' operator applied to it (as it does not have a memory location).
Register should only be used for variables that require quick access - such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.
static - Storage Class
static is the default storage class for global variables. The two variables below (count and road) both have a static storage class.
static int Count;
int Road;
{
printf("%d\n", Road);
}
|
static variables can be 'seen' within all functions in this source file. At link time, the static variables defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.
void func(void);
static count=10; /* Global variable - static is the default */
main()
{
while (count--)
{
func();
}
}
void func( void )
{
static i = 5;
i++;
printf("i is %d and count is %d\n", i, count);
}
This will produce following result
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
|
NOTE : Here keyword
void means function does not return anything and it does not take any parameter. You can memoriese void as nothing. static variables are initialized to 0 automatically.
Comments
Post a Comment