参考博客:https://blog.csdn.net/guotianqing/article/details/79828100
看个例子:
#include <stdio.h> void fn(void) { int n = 10; printf("n=%d\n", n); n++; printf("n++=%d\n", n); } void fn_static(void) { static int n = 10; printf("static n=%d\n", n); n++; printf("n++=%d\n", n); } int main(void) { fn(); printf("--------------------\n"); fn_static(); printf("--------------------\n"); fn(); printf("--------------------\n"); fn_static(); return 0; }
输出:
n=10
n++=11
--------------------
static n=10
n++=11
--------------------
n=10
n++=11
--------------------
static n=11
n++=12
--------------------------------
1、静态局部变量使用static修饰符定义,即使在声明时未赋初值,编译器也会把它初始化为0,且静态局部变量存储于进程的全局数据区,即使函数返回,它的值也会保持不变
2、普通局部变量是再熟悉不过的变量了,在任何一个函数内部定义的变量(不加static修饰符)都属于这个范畴
3、全局变量定义在函数体外部,在全局数据区分配存储空间,且编译器会自动对其初始化
4、在定义不需要与其他文件共享的全局变量时,加上static关键字能够有效地降低程序模块之间的耦合,避免不同文件同名变量的冲突,且不会误使用。