这个问题在这里已经有了答案:
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++ 中格式良好,因为具有静态存储持续时间的局部变量不是在启动期间初始化(常量表达式有一些异常(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/