STORAGE CLASSES in C


STORAGE CLASSES

These features of the function include scope and visibility.

  • Automatic

  • External

  • Static

  • Register.


1. Automatic:

   The keyword is auto

   Default storage class for all the variables declared inside a function block. So it is rarely used.

#include <stdio.h>


int main() {

auto int a = 10;

printf("%d ",++a);

{

int a = 20;

printf("%d ",a); // 20 will be printed since it is the local value of a


}

printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.

}



2. External:

  • The keyword is extern

  • It is not within the same block.

  • When a variable or function is declared with "extern", it tells the compiler that the symbol is defined elsewhere and the linker will resolve it at link time. This is useful when you want to use a variable or function from another file without redefining it



//External storage

#include <stdio.h>
int main() {
    extern int a;
    printf("%d",a);
   
    return 0;
}
int a = 20;


3. Static:

    The keyword is static.

    The scope will be local 

    The usage of this keyword is until the program ends the value will sustained


//Static storage

#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main () {

    printf("%d %c %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}


4. Register:

    The keyword is register.

    Faster than other storage classes but cannot obtain the values of the register using a pointer.


//Register Storage

#include <stdio.h>
int main() {
    register int a; // variable a is allocated memory in the CPU register.
//  The initial default value of a is 1.

    printf("%d",a);
    return 0;
//  printf("%d",&a);
}






Post a Comment

0 Comments