数组作为复合文字 [英] Array as compound literal

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

问题描述

在C99中,我们可以将复合文字用作未命名的数组.

In C99 we can use compound literals as unnamed array.

但这是文字常量,例如100'c'123.4f等.

But are this literals constants like for example 100, 'c', 123.4f, etc.

我注意到我可以做到:

((int []) {1,2,3})[0] = 100;

而且,我没有编译错误,并且可以猜测该未命名数组的第一个元素被修改为100.

and, I have no compilation error and is guessable that the first element of that unnamed array is modified with 100.

因此,与复合文字一样,数组似乎是左值而不是常量值.

So it seems as array as compound literal are lvalue and not constant value.

推荐答案

这是一个左值,如果我们查看

It is an lvalue, we can see this if we look at the draft C99 standard section 6.5.2.5 Compound literals it says (emphasis mine):

如果类型名称指定了未知大小的数组,则大小为 由6.7.8中指定的初始化程序列表确定,以及类型 复合文字的含义是完整数组类型的含义.否则 (当类型名称指定对象类型时), 复合文字是由类型名称指定的文字. 无论哪种情况, 结果是左值.

If the type name specifies an array of unknown size, the size is determined by the initializer list as specified in 6.7.8, and the type of the compound literal is that of the completed array type. Otherwise (when the type name specifies an object type), the type of the compound literal is that specified by the type name. In either case, the result is an lvalue.

如果要使用 const 版本,则稍后在同一部分中将给出以下示例:

If you want a const version, later on in the same section it gives the following example:

示例4可以通过以下方式指定只读复合文字 像这样的构造:

EXAMPLE 4 A read-only compound literal can be specified through constructions like:

(const float []){1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6}

我们可以在Dobb博士的文章 The新增C:复合文字,并说:

We can find an explanation of the terminology in this Dr Dobb's article The New C: Compound Literals and says:

复合文字不是真正的常量,因为 文字可能会更改,如稍后所示.这使我们有点 术语. C99和C90标准[2,3]使用恒定"一词 对于代表真正不变的价值的代币 无法修改语言.因此,10和3.14是整数 十进制常数和类型为double的浮点常数. 文字"一词​​用于表示以下内容的值: 可能不是那么恒定.例如,早期的C实现 允许修改带引号的字符串的值. C90和C99 通过说任何程序都不能修改字符串来禁止这种做法 文字具有未定义的行为,这是标准的说法 它可能会起作用,或者程序可能会以神秘方式失败. [...]

Compound literals are not true constants in that the value of the literal might change, as is shown later. This brings us to a bit of terminology. The C99 and C90 Standards [2, 3] use the word "constant" for tokens that represent truly unchangeable values that are impossible to modify in the language. Thus, 10 and 3.14 are an integer decimal constant and a floating constant of type double, respectively. The word "literal" is used for the representation of a value that might not be so constant. For example, early C implementations permitted the values of quoted strings to be modified. C90 and C99 banned the practice by saying that any program than modified a string literal had undefined behavior, which is the Standard’s way of saying it might work, or the program might fail in a mysterious way. [...]

这篇关于数组作为复合文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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