C储存类与作用域

1. 作用域

任何一种编程中,作用域是程序中定义的变量所存在的区域,超过该区域变量就不能被访问。C 语言中有三个地方可以声明变量:
函数或块内部的局部变量
在所有函数外部的全局变量
在形式参数的函数参数定义中

局部变量

在某个函数或块的内部声明的变量称为局部变量。它们只能被该函数或该代码块内部的语句使用。
局部变量在函数外部是不可知的。

全局变量

全局变量是定义在函数外部,通常是在程序的顶部。全局变量在整个程序生命周期内都是有效的,在任意的函数内部能访问全局变量。
在程序中,局部变量和全局变量的名称可以相同,但是在函数内,如果两个名字相同,会使用局部变量值,全局变量不会被使用。

#include <stdio.h>
 
/* 全局变量声明 */
int g = 20;
 
int main ()
{
  /* 局部变量声明 */
  int g = 10;
 
  printf ("value of g = %d\n",  g);
 
  return 0;
}
输出:
value of g = 10

形式参数

函数的参数,形式参数,被当作该函数内的局部变量,如果与全局变量同名它们会优先使用。

2.储存类

下面列出 C 程序中可用的存储类:
auto
register
static
extern

auto储存类

auto是所有局部变量的默认储存类
定义在函数中的变量默认为 auto 存储类,这意味着它们在函数开始时被创建,在函数结束时被销毁。

{
	int mount;
    auto int month;
}
# auto 只能用在函数内,即 auto 只能修饰局部变量

register储存类

register 存储类定义存储在寄存器,所以变量的访问速度更快,但是它不能直接取地址,因为它不是存储在 RAM 中的。在需要频繁访问的变量上使用 register 存储类可以提高程序的运行速度。
这意味着变量的最大尺寸等于寄存器的大小(通常是一个字),且不能对它应用一元的 ‘&’ 运算符(因为它没有内存位置)。

register int  miles;

寄存器只用于需要快速访问的变量,比如计数器。还应注意的是,定义 ‘register’ 并不意味着变量将被存储在寄存器中,它意味着变量可能存储在寄存器中,这取决于硬件和实现的限制。

static储存类

static 存储类指示编译器在程序的生命周期内保持局部变量的存在,而不需要在每次它进入和离开作用域时进行创建和销毁。
static 修饰局部变量可以在函数调用之间保持局部变量的值。
static 修饰符也可以应用于全局变量。当 static 修饰全局变量时,会使变量的作用域限制在声明它的文件内。

#include <stdio.h>

/* 函数声明 */
void func1(void);

static int count=10;        /* 全局变量 - static 是默认的 */

int main()
{
 while (count--) {
     func1();
 }
 return 0;
}

void func1(void)
{
/* 'thingy' 是 'func1' 的局部变量 - 只初始化一次
* 每次调用函数 'func1' 'thingy' 值不会被重置。
*/                
 static int thingy=5;
 thingy++;
 printf(" thingy 为 %d , count 为 %d\n", thingy, count);
}

在函数外部定义变量默认为static全局变量,在内部则需定义static,然后每次调用都会初始化一次

# 加static
 thingy 为 6 , count 为 9
 thingy 为 7 , count 为 8
 thingy 为 8 , count 为 7
 thingy 为 9 , count 为 6
 thingy 为 10 , count 为 5
 thingy 为 11 , count 为 4
 thingy 为 12 , count 为 3
 thingy 为 13 , count 为 2
 thingy 为 14 , count 为 1
 thingy 为 15 , count 为 0
 # 不加static
 thingy 为 6 , count 为 9
 thingy 为 6 , count 为 8
 thingy 为 6 , count 为 7
 thingy 为 6 , count 为 6
 thingy 为 6 , count 为 5
 thingy 为 6 , count 为 4
 thingy 为 6 , count 为 3
 thingy 为 6 , count 为 2
 thingy 为 6 , count 为 1
 thingy 为 6 , count 为 0

extern储存类

extern 存储类用于定义在其他文件中声明的全局变量或函数。
当使用 extern 关键字时,不会为变量分配任何存储空间,而只是指示编译器该变量在其他文件中定义。
当您有多个文件且定义了一个可以在其他文件中使用的全局变量或函数时,可以在其他文件中使用 extern 来得到已定义的变量或函数的引用。
main.c

#include <stdio.h>
 
int count ;
extern void write_extern();
 
int main()
{
   count = 5;
   write_extern();
}

support.c

#include <stdio.h>
 
extern int count;
 
void write_extern(void)
{
   printf("count is %d\n", count);
}

输出:

count is 5

猜你喜欢

转载自blog.csdn.net/weixin_45636780/article/details/132008044
今日推荐