Storage Class
Within a C programme, a storage class defines the scope (visibility) and lifetime of variables and/or functions. They come before the type they modify. Following are storage classes available in C:
- The Auto Storage Class: For all local variables, this storage class is the default one. The preceding example declares two variables in the same storage class. The keyword 'auto' can be used only within functions, i.e. within local variables.
#include
#include
void main()
{
auto int i=1;
{
auto int i=2;
printf("%d",i);
}
print(%d",i);
getch();
}
output:
2 1
- • The register Storage Class: It is used to specify local variables that should be saved in a register rather than RAM. This signifies that the variable's maximum size equals the register size, and it cannot be used with the unary '&' operator. Only use the register for variables that require immediate access, such as counters. It's also worth noting that just because'register' is defined doesn't ensure the variable will be put in a register. It signifies that, depending on hardware and implementation constraints, it MIGHT be saved in a register.
#include
#include
main()
{
register int a=10,b=5,ans;
ans = a+b;
printf("add:%d",ans);
return 0;
}
output:
add:15
- • The static Storage Class: It instructs the compiler to retain a local variable in existence throughout the program's lifetime rather than creating and destroying it each time it comes into and goes out of scope. As a result, making local variables static ensures that their values are preserved between function calls. The static modifier can be used on global variables as well. When you do this, the scope of that variable is limited to the file in which it is declared. When the keyword static is applied on a global variable in C programming, just one copy of that member is shared by all objects in that class.
#include
#include
void next(void);
static int c = 8; /* global variable */
main()
{
while(c<10)
{
next();
c++;
}
return 0;
}
void next(void) /* function definition */
{
static int i = 12; /* local static variable */
i++;
printf("i is %d and c is %d\n", i,c);
getch();
}
output:
i =13 and c=8
i =14 and c=9
- The extern Storage Class: It is used to give a reference to a global variable that is viewable in ALL application files. The variable cannot be initialised when you use 'extern,' but it does direct the variable name to a previously established storage location. When you have many files and specify a global variable or function that will be utilised in other files, extern is used in another file to provide a reference to the defined variable or function. To clarify, extern is a keyword that is used to declare a global variable or function in a different file.
#include
#include
extern int i = 7;
main()
{
printf("value of the external i is =%d\n",i);
return 0;
}
output:
value of the external i is 7