c - 不了解C中static int的功能

标签 c function static int

我试图理解这段代码,但我不知道为什么静态变量的数量有时会改变,有时不会。

#include <stdio.h>
int func1 (int x)
{
    extern int a;
    static int y=0;
    printf("%d\n%d\n",a,y);
    a=x+5; y=x+1;
    {int y=10; printf("%d\n",y);}
    return y;
}
int a;
int main()
{
    a=func1(1);
    printf("%d\n",a);
    {
        int a=1;
        printf("%d\n", a);
    }
    a=func1(a);
    printf("%d",a);
    return 0;
}

这是输出:

0

0

10

2

1

2

2

10

3

起初,当a = func(1)运行时,y声明为0,然后变为2 并打印 2。但是当 a = func(a)a2 时,我预计 y 会变成 0static int y = 0y 不会改变。为什么它没有发生?

最佳答案

从概念上讲,静态对象在创建时就已初始化。

静态对象的生命周期从程序开始执行开始,一直持续到执行结束。

因此,当程序开始执行时,y 被初始化为 0。之后,它的值只有在被修改时才会改变,就像赋值语句一样。定义它的语句 static int y = 0; 在初始化后不会修改它。

关于c - 不了解C中static int的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55620830/

相关文章:

c++ - 为什么免费调用两次时会崩溃?

javascript - 获取 WebAssembly 导出函数的地址?

Python ctypes - 在头文件中调用静态内联函数?

php - 最终的静态类方法是否可能?

c++ - 是否有像 docco 这样的 C/C++ 源代码文档生成器?

c - C 中的基本数组和函数 - 自学

c++ - 如何通过包含相应的 .h 文件从 .cpp 中获取函数/类定义?

jquery $(this).parent()... 无法从外部调用的函数中工作

function - 使用相同变量定义函数的最优雅/有效的方法

java - 警告 : The type parameter E is hiding the type E when using an inner class