Storage Classes : A storage class defines the scope (visibility) and life-time of variables and/or functions within a C program.
We have four different storage classes in a C program.
|
Storage
class |
Purpose |
|
auto |
It is a default storage class |
|
register |
It is a variable which is stored inside a Register. |
|
static |
It is a local variable which is capable of returning a value even when control is
transferred to the function call. |
|
extern |
It is a global variable. |
Auto storage class : The 'auto' storage class is the default storage class for all local variables.
Example :
int car; // default auto
auto int car; // auto defined using auto keyword
The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables.
Example :
#include<stdio.h>
int main ()
{
int a; // auto
char b; // auto
float c; // auto
printf("%d %c %f", a,b,c);
return 0;
}
Output ---> Garbage Garbage Garbage
Register storage class : This storage class is implemented for classifying local variables whose value needs to be saved in a register in place of RAM (Random Access Memory).
This is implemented when you want your variable the maximum size equivalent to the size of the register. It uses the keyword 'register'.
Example : register int apple;
Register variables are used when implementing looping in counter variables to make program execution fast.
Register variables work faster than variables stored in RAM (primary memory).
Example:
#include<stdio.h>
int main()
{
register int a; // cpu assign default value of a is 0
print("%d",a);
}
Output---> 0
Static storage class : This storage class uses static variables that are used popularly for writing programs in C language.
Static variables preserve the value of a variable even when the scope limit exceeds.
Static storage class has its scope local to the function in which it is defined.
On the other hand, global static variables can be accessed in any part of your program.
The default value assigned is '0' by the C compiler.
The keyword used to define this storage class is 'static'.
Example : static int a=6;
Example :
#include<stdio.h>
static int a=2;
static char b='h';
static float c=5.0;
void main()
{
print("%d%c%f",a,b,c);
}
Output---> 2, h, 5.0
Extern storage class : The extern storage class is used to feature a variable to be used from within different blocks of the same program.
An extern variable is a global variable which is assigned with a value that can be accessed and used within the entire program.
Moreover, a global variable can be explicitly made an extern variable by implementing the keyword 'extern' preceded the variable name.
Example :
#include <stdio.h>
int val;
extern void
funExtern();
main()
{
val = 10;
funExtern();
}
No comments:
Post a Comment