C语言:存储类

这是很基础的教程,我只是写给自己看,作为一个学习笔记记录一下,如果正在阅读的你觉得简单,请不要批评,可以关掉选择离开

如何学好一门编程语言

  • 掌握基础知识,为将来进一步学习打下良好的基础。
  • 上机实践,通过大量的例题学习怎么设计算法,培养解题思路。
  • 养成良好的编码习惯,注释一定要写,要不然保你一周后自己写的代码都不认识了。

存储类定义 C 程序中变量或函数的范围和生命周期。通常放置在他们所修饰的类型之前。C程序中的存储类有:

  • auto
  • register
  • static
  • extern

auto存储类

auto 是所有局部变量默认的存储类。

{
   int mount;
   auto int month;
}

上面的实例定义了两个带有相同存储类的变量,auto 只能用在函数内,即 auto 只能修饰局部变量。

register 存储类

register 用于定义存储在寄存器中的局部变量,而不是 RAM 中的局部变量。且不能对它应用一元的 '&' 运算符(因为它没有内存位置)。

{
   register int  miles;
}

寄存器只用于需要快速访问的变量,比如计数器。

还应注意的是,定义 'register' 并不意味着变量将被存储在寄存器中,它意味着变量可能存储在寄存器中,这取决于硬件和实现的限制。

static 存储类

static 修饰符用于定义 全局变量。作用域限制在声明它的.c文件内。

#include <stdio.h>

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

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

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

void func1(void) {
  /* a 是 'func1' 的局部变量(只初始化一次)
   * 每次调用函数 'func1'时,'a' 值不会被重置。*/
  static int a = 5;
  a++;
  printf(" a: %d, count: %d\n", a, count);
}
//a: 6, count: 9
//a: 7, count: 8
//a: 8, count: 7
//a: 9, count: 6
//a: 10, count: 5
//a: 11, count: 4
//a: 12, count: 3
//a: 13, count: 2
//a: 14, count: 1
//a: 15, count: 0
结果

另外 C 不支持在函数外返回局部变量的地址,除非定义局部变量为 static 变量。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* 要生成和返回随机数的函数 */
int *getRandom() {
    static int r[10];
    int i;

    /* 设置种子 */
    srand((unsigned) time(NULL));
    for (i = 0; i < 10; ++i) {
        r[i] = rand();
        printf("r[%d] = %d\n", i, r[i]);
    }
    return r;
}

/* 要调用上面定义函数的主函数 */
int main() {
    int *p; /* 一个指向整数的指针 */
    int i;

    p = getRandom();
    for (i = 0; i < 10; i++) {
        printf("*(p + %d) : %d\n", i, *(p + i));
    }

    return 0;
}

extern 存储类

使用 extern 声明一个变量或函数,而这个变量或函数在其他 .c 文件中定义。

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

在这里,第二个文件中的 extern 关键字用于声明已经在第一个文件 main.c 中定义的 count。现在 ,编译这两个文件,如下所示:

 $ gcc main.c support.c

这会产生 a.out 可执行程序,当程序被执行时,它会产生下列结果:

count is 5

参考

菜鸟教程

posted @ 2021-05-07 22:27  凌逆战  阅读(179)  评论(0)    收藏  举报