c++ - C++中静态变量的存储位置是什么时候确定的?

标签 c++ c build static-variables

这个问题在这里已经有了答案:





Difference between initialization of static variables in C and C++

(3 个回答)


去年关闭。




我有以下简单的程序:

int main()
{
    int x = 5;
    static int y = x;
    return (0);
}
用 gcc 编译它,它会为 static int y = x; 行产生错误因为“初始化元素不是常数”。我认为这是由于 y是一个静态变量,它的存储位置(data/bss)和初始值需要在编译时知道。
但是,当使用 g++ 编译时,我没有收到任何错误并且程序运行良好(打印 y 打印 5)。
我的问题是:
  • 我的假设正确吗?
  • 如果是这样,为什么可以在 C++ 中对静态变量进行这样的初始化?
  • 最佳答案

    您的程序在 C++ 中格式良好,因为具有静态存储持续时间的局部变量不是在启动期间初始化(常量表达式有一些异常(exception);在此示例中不适用),但在第一次控制通过它们的声明时,初始化程序表达式,包含局部非静态变量 x , 是现成的。
    引用 cppreference / Storage duration - Static local variables [ 重点矿]

    Variables declared at block scope with the specifier static or thread_local (since C++11) have static or thread (since C++11) 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 中的静态初始化并不遵循相同的规则。来自 cppreference / C language - Initialization :

    When initializing an object of static or thread-local storage duration, every expression in the initializer must be a constant expression or string literal.


    因此,您的程序在 C 中格式不正确。

    关于c++ - C++中静态变量的存储位置是什么时候确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65716519/

    相关文章:

    c++ - 错误 : Expression must be a modifiable lvalue

    c - sigaction 和 signal 有什么区别?

    java - Maven 安装后出现问题 - mvn install 尝试下载无法访问的文件

    c++ - 将 qwidget 上的当前项目保存为图像

    c++ - 如何在C++中输出欧元符号

    无法使用 "page-as-heap"选项运行 valgrind Massif

    c - C语言去除字符串中的标点符号

    intellij-idea - Intellij IDEA - JavaFX 打包程序 : access denied

    git - 在 Azure Devops 中,有没有办法从单个构建定义的多个存储库中获取源代码?

    c++ - 如何在第一次使用之前将静态数组保留在内存之外