下面是否完美定义:
int x = 42, y = x;
即严格等价于:
int x = 42;
int y = x;
编辑:问题与风格无关(我知道这是错误的......),问题是“理论上的”
最佳答案
正确答案是
int x = 42, y = x;
和
int x = 42;
int y = x;
通常是等价的(不严格)。
考虑到标准 § 8 声明符 [dcl.decl]:
3
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
并在脚注[100]中进一步说明:
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;
is usually equivalent to
T D1; T D2; ... T Dn;
where T is a decl-specifier-seq and each Di is an init-declarator.
以上保证
x = 42
和y = x
将被单独评估。然而,作为@Praetorian在评论中正确指出,脚注不规范。这意味着评估的顺序没有明确定义,实现者也可以以相反的顺序实现声明的评估(即。
T Dn; ...T D2; T D1;
).有人可能会争辩说,逗号运算符可以保证从左到右求值。然而,事实并非如此。根据 K & R [K & R II, 3.6 p.63],这也适用于 C++:
The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.
关于c++ - 用逗号相互依赖初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24224115/