问题描述
将以下代码放在作用域/函数中时,无法编译,编译器将产生错误,指出以下内容: initializer元素不是常量
.在GCC和MSVC上都会发生这种情况.
The following code cannot be compiled when put inside a scope/function, the compiler will produce an error stating something along the lines of: initializer element is not constant
. This happens on GCC as well as MSVC.
static const char *const *const list = (const char *const[]){"abc", "def", "xyz"};
但是,如果将代码放在任何函数之外,并且将 list
初始化为具有静态存储持续时间的全局变量,则代码可以正常编译,并且不会产生任何警告或错误.仅当 list
是非静态的时,它也可以在作用域/函数中初始化.
But when the code is put outside of any function and list
is initialized as a global variable with static storage duration, the code compiles fine and doesn't produce any warnings or errors. Only when list
is non-static, it can be initialized within a scope/function as well.
cppreference文档中的以下引文引起了我的注意:/p>
The following quote from the cppreference docs has caught my eye:
这是否可以肯定地说,具有静态存储持续时间的局部变量不能用复合文字初始化?
Does this mean that it's safe to say that local variables with a static storage duration cannot be initialized with a compound literal?
推荐答案
具有静态存储持续时间的对象可以通过常量表达式初始化.复合文字不是常量(实际上它们是左值).您不能使用带有复合文字的静态存储持续时间来初始化对象(尽管GCC允许它作为扩展名).
Objects with static storage duration can be initialized by constant expressions. Compound literals are not constants (in fact they are lvalues). You can't initialize objects with static storage duration with compound literals (though GCC allow it as extension).
这篇关于用复合文字初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!