C Storage Classes
C Storage Classes
C storage classes define the scope, default initial value, and lifetime of a variable. The initial default value refers to the value present in the variables as default before they initialized, and lifetime refers to the variable’s duration of life.
1) Auto Storage Class
Variables are formed in a function and whose storage class is not defined initially fall in this category automatically. The variables define using the auto storage class are called local variables. Only the block in which the auto variable is declared can access it.
Syntax
int a; auto int a; //Both are the same.
The example above defines two variables within the same storage class. ‘auto’ can only be used within functions, i.e., local variables.
2) Static Storage Class
Static variables are a little bit technical as their lifetime is throughout the program. But their scope is limited to the function they are initialized in. It comes in handy when we are changing their value in the program as the program will store the new value, overwriting the previous one.
when static is used the global variable, it causes all the objects of its class is share only one copy of that member
Syntax
static int a;
3) Register Storage Class
It is very similar to the Auto storage class as its scope is limited to the function it is defined in, the initial default value is 0, and the lifetime is till the end of the function block.
It is usually used for the programs that need to be accessed faster than the other or used frequently. The register storage class is used to define local variables that should be stored in a register instead of RAM.
Syntax
register int a;
4) Extern Storage Class
Using extern storage, we inform our compiler that the variable is already declared at some other place. The extern storage class is used to give a reference to a global variable
For all the program files we can use the same variable with the same space, without allocating its new memory and accessing the same variable in some other file. Its syntax is simple as we have to use the extern keyword, and it will automatically access it from the other file.
Syntax
extern int a;
Program
#include <stdio.h> int myfunc(int a, int b) { // auto int myVar; static int myVar; myVar ++; printf("The myVar is %d\n", myVar); // myVar = a+b; return myVar; } int main() { int a; int a; // Declaration - Telling the compiler about the variable (No space reserved) // Definition - Declaration + space reservation register int myVar = myfunc(3, 5); myVar = myfunc(3, 5); myVar = myfunc(3, 5); myVar = myfunc(3, 5); // printf("The myVar is %d\n", myVar); return 0; }
Output
The myVar is 1 The myVar is 2 The myVar is 3 The myVar is 4
Also, read an array of structures in C.