在函数内部时如何不重新分配静态变量

how does a static variable not get reassigned when inside the function

我对 this 问题的答案有疑问,但我无法对此发表评论,因为我的代表少于 50 人。

我想知道答案 foo() 被多次调用并且静态变量被分配相同的次数。那为什么每次都没有把static变量重新赋值到10呢?

实际上 static 个变量可以 重新分配 。但不能重新定义.

一旦定义了 static 变量,它就无法在程序的整个生命周期内重新定义。但是我们可以改变这个值。

你的答案比较简短,但让我详细说明一下。

任何对象,都有一个storage duration。存储时长决定了对象(或变量)的"lifetime"

静态存储是存储期限之一,用关键字static标记。现在,为了详细说明寿命,让我们查看 C11 标准的相关部分,第 6.2.4 章。

从第 2 段开始,

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address and retains its last-stored value throughout its lifetime. [....]

因此,最后存储的值将在整个生命周期内保留。

现在,对于具有静态存储持续时间的对象,第 3 段,

An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

现在,关于你的问题,你看到的语句是初始化,根据指定的规则,它只发生一次(程序启动之前),所以初始化对于多个函数调用不会重复。变量保留最后存储的值。

当你定义一个静态或全局变量时,它进入内存模型的数据段,并在程序的生命周期内占用该分配,当然,范围与定义它的每个变量相关联。所以当你再次进入这个函数时,这个变量是存在的,它也会记住上次的内容。所以理想情况下你不能重新定义一个变量,如果你用条件绑定它而不是范围将保护它因此它是一个新变量。