逗号分隔变量定义中的先序关系
Sequence-before relation in comma-separated variable definitions
让我们从以下示例代码开始:
int a = 0, b = a++, c = a;
a++
是否排在 a
之前(在 c = a
内)? a++
和 a
似乎符合完整表达式的条件,根据 cppreference (规则 1),答案应该是肯定的。但我不确定。
是的。正如 指出的那样,这不是逗号运算符,而是 init-declarator-list。从 [dcl.decl] 我们有:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
用脚注澄清:
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.
有两个例外,一个是隐藏类型的名称,另一个是 auto
,两者都不适用。所以最终,您拥有的代码完全等同于:
int a = 0;
int b = a++;
int c = a;
你应该首先写下哪个,因为它不需要搜索标准来确保你做的事情有效!
让我们从以下示例代码开始:
int a = 0, b = a++, c = a;
a++
是否排在 a
之前(在 c = a
内)? a++
和 a
似乎符合完整表达式的条件,根据 cppreference (规则 1),答案应该是肯定的。但我不确定。
是的。正如
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
用脚注澄清:
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 eachDi
is an init-declarator.
有两个例外,一个是隐藏类型的名称,另一个是 auto
,两者都不适用。所以最终,您拥有的代码完全等同于:
int a = 0;
int b = a++;
int c = a;
你应该首先写下哪个,因为它不需要搜索标准来确保你做的事情有效!