首页 > 解决方案 > 这个“静态”变量的定义是错误的、误导的,还是两者都不是?

问题描述

根据https://www.learn-c.org/en/Static

默认情况下,变量在定义它们的范围内是本地的。可以将变量声明为静态变量,以将其范围扩大到包含它们的文件。因此,可以在文件中的任何位置访问这些变量。

提供了两个代码示例。首先,在函数返回后从内存中删除
局部变量的示例:int countrunner()

#include<stdio.h>
int runner() {
    int count = 0;
    count++;
    return count;
}

int main()
{
    printf("%d ", runner());
    printf("%d ", runner());
    return 0;
}

输出是:1 1

下一个给出的例子是count静态的:

#include<stdio.h>
int runner()
{
    static int count = 0;
    count++;
    return count;
}

int main()
{
    printf("%d ", runner());
    printf("%d ", runner());
    return 0;
}

这次的输出是:1 2.

count在此示例中增加到 2,因为它没有在返回时从内存中删除runner()
...但是,这似乎与页面开头关于在文件中的任何位置访问静态变量的语句无关。这两个示例仅表明static允许count在多次调用时保留在内存中runner()(并且每次调用都没有设置为 0)。它们没有显示是否count可以“在文件内的任何位置”访问,因为main()只是打印runner()返回的任何内容。

为了说明我的观点,我做了一个示例,显示文件内的任何地方static都无法count()访问:

#include<stdio.h>
void runner()
{
    static int count = 0;
    count++;
    return;
}

int main()
{
    runner();
    printf("%d ", count);
    runner();
    printf("%d ", count);
    return 0;
}

输出是:

prog.c: In function 'main':
prog.c:12:23: error: 'count' undeclared (first use in this function)
         printf("%d ", count);
                       ^
prog.c:12:23: note: each undeclared identifier is reported only once for each function it appears in

这就是我所期望的。

我又举了一个例子,这个用途x可以被runner()和访问main()

#include<stdio.h>
int x = 0;
void runner()
{
    static int count = 0;
    count++;
    x = count;
    return;
}

int main()
{
    runner();
    printf("%d ", x);
    runner();
    printf("%d ", x);
    return 0;
}

输出是:1 2

这个问题顶部的引用是不正确的、误导的,还是两者都不是?我误解了语义问题吗?

标签: cscopestaticlifetime

解决方案


你是对的,报价是错误的。在功能块中声明一个变量static会增加它的生命周期,而不是它的作用域。(范围是您可以使用名称的代码部分。)

我真的无法想象解释“在文件中的任何位置访问”的正确方法。如果您有指向此类变量的指针,则在其他函数中取消引用该指针是有效的,但对于所有函数都是如此,而不仅仅是同一文件中的函数。

可能是时候停止使用该网站了。


推荐阅读