c++ - 为什么 static 修饰符会阻止其变量被重新分配新值?

标签 c++ static initialization variable-assignment modifiers

一个最小的工作示例如下:

#include <iostream>

void func()
{
    static int i = 5;
    std::cout << i << std::endl;
    i = 42;
    std::cout << i << std::endl;
}

int main( int argc, char ** argv )
{
    std::cout << "this is main()" << std::endl;
    func();
    func();
    return 0;
}

其输出如下:

this is main()
i is 5
i is 42
i is 42
i is 42
变量 int

Static 修饰符使 int 的值在整个进程的生命周期内保持不变,而静态存储不存储在堆栈;因此,该值从函数的一次调用传递到另一次调用。

但是,intfunc() 开始时被重新赋值为 5,当 func() 被第二次调用时时间。

那么,为什么这个例子输出的是 i = 42 而不是 i = 5

最佳答案

However, int is re-assigned to the value of 5 at the beginning of func() when func() is called second time.

不,这不是assignment , 但是 initialization . Static local variables仅初始化一次,即在第一次调用 func() 时。

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

关于c++ - 为什么 static 修饰符会阻止其变量被重新分配新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43435792/

相关文章:

c++ - 为什么第一行出现了除零以外的其他值?

java - 在 Controller JavaFX 的初始化方法中获取 NullPointerException

c++ - 使用临时对象来初始化线程

c++ - 二叉搜索树(BST)返回左 child 被视为函数,不明白

c# - 技术实现多态性但节省 4 个字节

java - Java 中一个类的多个静态实例?

c - ‘DisplayMenu’ 的静态声明遵循非静态声明

c++ - 为什么 select(QTextCursor::BlockUnderCursor) 包含一个额外的垃圾字符?

c++ - Cygwin GDB 在尝试启动程序时出现错误 193

c++ - dos.h 是一个什么样的库(静态的还是动态的)?