静态变量

chu*_*kki 3 c

任何人都可以解释何时应该使用静态变量以及为什么?

hay*_*lem 8

staticC中关键字有两种不同的用法:

  • 函数范围中的静态声明
  • 函数范围之外的静态声明

(MOSTLY)EVIL:函数中的静态变量

函数中的静态变量用作"记忆"状态.

基本上,只有在第一次调用变量时,您的变量才会初始化为默认值,然后在以后的所有调用中保留其先前的值.

如果你需要记住这样的状态,这可能是有用的,但是这种静态的使用通常是不受欢迎的,因为它们几乎是伪装的全局变量:它们将耗尽你的记忆,直到你的过程终止一次.

因此,一般来说,制作本地化的功能是EVIL/BAD.

例:

#include <stdio.h>


void  ping() {
  static int counter = 0;

  return (++counter);
}

int   main(int ac, char **av) {
  print("%d\n", ping()); // outputs 1
  print("%d\n", ping()); // outputs 2
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

输出:

1
2
Run Code Online (Sandbox Code Playgroud)

(MOSTLY)GOOD:函数范围之外的静态变量

您可以在变量或函数上使用函数外部的静态(毕竟,它也是一个变量,并指向一个内存地址).

它的作用是将该变量的使用限制在包含它的文件中.你不能从别的地方叫它.虽然它仍然意味着函数/ var是"全局的",因为它会消耗你的内存,直到程序终止,至少它具有不污染你的"命名空间"的风格.

这很有趣,因为这样您就可以在项目的不同文件中使用具有相同名称的小实用程序函数.

因此,一般来说,制作本地化的功能是好的.

例:

example.h文件

#ifndef __EXAMPLE_H__
# define __EXAMPLE_H__

void  function_in_other_file(void);

#endif
Run Code Online (Sandbox Code Playgroud)

在file1.c

#include <stdio.h>

#include "example.h"

static void  test(void);


void test(void) {
  printf("file1.c: test()\n");
}

int   main(int ac, char **av) {
  test();  // calls the test function declared above (prints "file1.c: test()")
  function_in_other_file();
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

file2.c中

#include <stdio.h>

#include "example.h"

static void  test(void); // that's a different test!!


void test(void) {
  printf("file2.c: test()\n");
}

void   function_in_other_file(void) {
  test();  // prints file2.c: test()
  return (0);
}
Run Code Online (Sandbox Code Playgroud)

输出:

file1.c: test()
file2.c: test()
Run Code Online (Sandbox Code Playgroud)

PS:如果你是一个纯粹主义者,不要开始向我扔石头:我知道静态变量不是邪恶的,它们也不是全局变量,函数不是变量,并且没有实际的"命名空间"(不要在C.中开始使用符号)但这是为了解释这里.

资源