以下程序给出的输出是1 1
而不是1 2
这是我使用static int count = 0
而不是单独的初始化count = 0
时的输出。
#include<stdio.h>
int fun()
{
static int count;
count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
这是否意味着单独的初始化会覆盖应该在调用之间保留值的静态声明?
我搜索了相当广泛的内容,但找不到任何明确证实我信念的答案。
count = 0;
是0到count
的显式赋值,每次调用函数时都会发生。
因此,您的输出。
写入static int count;
会将count
初始化为 0,因为它具有静态存储持续时间。这就是你想要的吗?
最后,fun
不是线程安全的,因为使用非原子类型并在没有互斥单元的情况下递增。
#include<stdio.h>
int fun()
{
static int count;
count = 0; // for static variables this is not a initialisation
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
count = 0
表示赋值而不是初始化
每次您呼叫fun()
时,count
将由0
分配
如果要获得正确的输出,请使用此代码
#include<stdio.h>
int fun()
{
static int count = 0;
count++;
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}