我学了一些 C 语言并发现了静态变量的解释。
他们展示了这段代码:
#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
我不明白为什么调用该函数两次就可以了,因为该行
static int count = 0;
实际上运行了两次...
我不明白这怎么可能......
您实际上可以声明它两次吗?还是编译器第二次会忽略它?
这是初始化定义所在的位置(静态/全局)really与未初始化的定义后跟赋值不同。
从历史上看,前者甚至曾经有不同的语法(int count /*no '=' here*/ 0;
).
当你这样做时:
int fun() {
static int count = 0;
//...
}
那么除了不同的范围(但不是生命周期)count
,它相当于:
static int count = 0; //wider scope, same lifetime
int fun() {
//...
}
在这两种情况下,静态变量都会在加载时初始化,通常与可执行文件中的其他静态变量和全局变量一起初始化。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)