首页 > 文章列表 > C语言中的不同存储类

C语言中的不同存储类

static auto extern
113 2023-08-20

问题

C语言中有哪些不同的存储类?用程序解释它们。

解决方案

存储类被定义为存在于C程序中的变量或函数的作用域和生命周期。

存储类

C语言中的存储类如下:

  • auto
  • extern
  • static
  • register

自动变量/局部变量

  • 关键字 - auto
  • 也称为局部变量
  • 作用域 -
    • 局部变量的作用域仅限于声明它们的块内。

    • 这些变量在块内部声明。

  • 默认值 - 垃圾值

示例

 演示

#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

  • Keyword − extern
  • These variables are declared outside the block and so they are also called global variables

  • Scope − Scope of a global variable is available throughout the program.

  • Default value − zero

Example

 Live Demo

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

Output

31

Static variables

  • Keyword − static
  • Scope − Scope of a static variable is that it retains its value throughout the program and in between function calls.
  • Static variables are initialized only once.
  • Default value − zero

Example

 Live Demo

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

Output

1    2    3

注册变量

  • 关键字 − register
  • 寄存器变量的值存储在CPU寄存器中,而不是存储在内存中,正常变量存储在内存中。

  • 寄存器是CPU中的临时存储单元。

示例

 演示

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

Output

1 2 3 4 5