用逗号相互初始化吗? [英] Interdependent initialization with commas?
问题描述
以下定义是否完美:
int x = 42, y = x;
即严格等同于:
int x = 42;
int y = x;
问题不是关于样式(我知道这是错误的...),问题是理论上的"
EDIT : the question is not about style (I know that it's wrong...), the question is "theoretical"
推荐答案
正确的答案是
int x = 42, y = x;
和
int x = 42;
int y = x;
通常是等效的(不严格).
考虑标准§8声明符[dcl.decl] :
3
分别对声明中的每个init-declarator进行分析,就好像它本身在声明中一样.
3
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
并在脚注[100]中进一步说明:
and in the footnote [100] further explains:
具有多个声明符的声明通常等效于相应的声明序列,每个声明都有一个 声明者.那是
A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is
T D1,D2,... Dn;
通常等同于
T D1; T D2; ... T Dn;
,其中T是decl-specifer-seq,每个Di是init声明符.
-
以上保证了
x = 42
和y = x
将被分别求值.但是,正如 @Praetorian 在评论中正确指出的那样,脚注不是规范性的.The above guarantees that
x = 42
andy = x
will be evaluated separately. However, as @Praetorian correctly pointed out in the comments, footnotes are not normative.这意味着评估的顺序没有很好地定义,实现者也可以以相反的顺序(即
T Dn; ...T D2; T D1;
)实现声明的评估.This means that the order of evaluation is not well defined and an implementer could as well implement the evaluation of the declarations in the reverse order (i.e,.
T Dn; ...T D2; T D1;
).有人可能会争辩说逗号运算符可以保证从左到右的评估.但是,事实并非如此.根据K& R [K& R II,第3.6页,第63页],也适用于C ++:
One might argue that the comma operator is guaranteed left to right evaluation. However, this not the case. According to the K & R [K & R II, 3.6 p.63], that also applies to C++:
分隔函数参数,声明中的变量等的逗号不是逗号运算符,也不保证从左到右的求值.
这篇关于用逗号相互初始化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!