STORAGE CLASSES in C



STORAGE CLASSES

These features of the function include scope and visibility.

In other words, A storage class defines the scope and lifetime of variables and/or functions within a program.

Types:

  • Automatic

  • External

  • Static

  • Register.


1. Automatic:

   A variable declared inside a functions without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. The keyword is auto.

Example 01:


#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


Example 02:

//External storage

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


3. Static:

The value of a static variable persists until the end of the program instead of creating and destroying it each time it comes into and goes out of scope. They are assigned 0 (zero) as default value by the computer.


Example 03:

void test();

main(){
test();
test();
test();
}

void test(){
static int a = 0;
a=a+1;
printf("%d\t",a)
}

4. Register:

    Register variable informs the compiler to store variable in register instead of memory.

Register variable has faster access than normal variable. Frequently used variables are kept in register. The keyword is register.

Example 04:


//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);
}






← Back Next →

Comments

Popular posts from this blog

Wrapper Class

Information Security & Essential Terminology

Information Security Threat Categories