用复合文字初始化变量 [英] Initializing variables with a compound literal

查看:80
本文介绍了用复合文字初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下代码放在作用域/函数中时,无法编译,编译器将产生错误,指出以下内容: 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:

复合文字评估的未命名对象具有静态如果复合文字出现在文件范围和如果复合文字出现在块中,则自动存储持续时间范围(在这种情况下,对象的生存期在封闭的块).

The unnamed object to which the compound literal evaluates has static storage duration if the compound literal occurs at file scope and automatic storage duration if the compound literal occurs at block scope (in which case the object's lifetime ends at the end of the enclosing block).

这是否可以肯定地说,具有静态存储持续时间的局部变量不能用复合文字初始化?

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).

这篇关于用复合文字初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆