Home  >  Article  >  Backend Development  >  Different storage classes in C language

Different storage classes in C language

PHPz
PHPzforward
2023-09-15 11:45:061225browse

Different storage classes in C language

Question

What are the different storage classes in C language? Interpret them with programs.

Solution

A storage class is defined as the scope and life cycle of a variable or function that exists in a C program.

Storage classes

The storage classes in C language are as follows:

  • auto
  • extern
  • static
  • register

Automatic variables/local variables

  • Keywords - auto
  • is also called local variable
  • Scope -
    • The scope of local variables is limited to the block in which they are declared.

    • These variables are declared inside the block.

  • Default Value - Garbage Value

Example

Demonstration

#include<stdio.h>
void main (){
   auto int i=1;{
      auto int i=2;{
         auto int i=3;
         printf ("%d",i);
      }
      printf("%d", i);
   }
   printf("%d", i);
}

Output

3 2 1

Global variables/external variables

  • Keywords - extern
  • These variables are declared outside the block so they are also Global variables are called

  • #Scope - The scope of a global variable is available throughout the program.

  • Default - Zero

Example

Live Demonstration

#include<stdio.h>
extern int i =1; /* this &lsquo;i&rsquo; is available throughout program */
main (){
   int i = 3; /* this &lsquo;i&#39; available only in main */
   printf ("%d", i);
   fun ();
}
fun (){
   printf ("%d", i);
}

Output

31

static variable

  • Keyword - static
  • Scope - The advantage of a static scope variable is that it is used throughout the program as well as Preserves its value between function calls.
  • Static variables are initialized only once.
  • Default value - zero
  • li>

Example

Live demonstration

#include<stdio.h>
main (){
   inc ();
   inc ();
   inc ();
}
inc (){
   static int i =1;
   printf ("%d", i);
   i++;
}

Output

1    2    3

Register variable

  • Keyword − register
  • The value of the register variable is stored in the CPU register rather than in memory , normal variables are stored in memory.

  • Register is a temporary storage unit in the CPU.

Example

Demonstration

#include<stdio.h>
main (){
   register int i;
   for (i=1; i< =5; i++)
      printf ("%d",i);
}

Output

1 2 3 4 5

The above is the detailed content of Different storage classes in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete