在静态声明后使用赋值语句

  • 本文关键字:赋值语句 静态 声明 c
  • 更新时间 :
  • 英文 :


以下程序给出的输出是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;
}

最新更新