c - 静态变量不维护它的范围?

标签 c static

我只是在玩,写了这个非常简单的代码

int main()
{
    static int Z=500;
    printf("\n Value of Z is:%d",Z);
    incrementZ(Z);
    printf("\n Value of Z is:%d",Z);
    incrementZ(Z);
    printf("\n Value of Z is:%d",Z);
}

void incrementZ(static int number)
{
    number++;
}

为什么静态变量在这里没有递增?

最佳答案

你在 Windows 上,所以检查 this link .

根据文档,static 将被任一可用的标准存储类替换。存在三种可能的情况,

  1. auto :如果标识符是形式参数或局部变量。
  2. extern:如果标识符是一个函数。
  3. 无存储类:如果标识符是全局变量。

它将允许编译,只产生一个警告 [C4042] 说类似的话

C4042 : identifier .. has bad storage class


但是,补充一下,在 linux gcc 上,这不符合要求。它会抛出一个错误说

error: storage class specifiers invalid in parameter declarations

关于c - 静态变量不维护它的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928614/

相关文章:

c - Firebird 数据库连接凭据

c - 使用指针变量分配数组元素值时,第三个数组元素不会打印出来

c - 我试图通过 ioctl 从驱动程序获得的以太网速度是恒定的,比如 57872Mbps,为什么?

c - 如何添加 for 循环的计数器并将其传递给 C 中的函数

qt5 : how to create and display custom qdialog from static function within a qthread

php - 获取当前的 ISO8601 日期/时间戳

c - yacc 缺少左括号的错误处理

c - 查找大于和小于数组中的数字

c++ - C/C++ : Static function in header file, 是什么意思?

java - 不能从静态上下文中引用非静态变量