gpt4 book ai didi

c++ - "a subsequent condition of that statement"的标准是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 23:21:39 25 4
gpt4 key购买 nike

N4567 标准禁止对先前在条件中声明的名称进行某些类型的重新声明,如下所示——根据标准(§3.3.3/4):

Names declared in the for-init-statement, the for-range-declaration, and in the condition of if, while, for, and switch statements are local to the if, while, for, or switch statement (including the controlled statement), and shall not be redeclared in a subsequent condition of that statement nor in the outermost block (or, for the if statement, any of the outermost blocks) of the controlled statement; see 6.4.

但是,考虑到以下代码可以正常编译,

int main(void) {
if (int i=10)
if (int i=20)
;
return 0;
}

我似乎不清楚“该语句的后续条件”究竟代表什么。

最佳答案

突出显示的“that”语句表示 ifwhileforswitch 语句定义名称,而不是由条件或迭代控制的子语句。

解释如下:

6.4/3: A name introduced by a declaration in a condition (either introduced by the decl-specifier-seq or the declara- tor of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition. If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed.

这就是为什么下面的陈述是有效的:

if (int i=10)
if (int i=20)
;

编译器不将 if (int i=20) 的声明分析为同一 if 语句的不同条件,而是作为受控子语句。并且由于 i 的第二个声明发生在条件中,因此在受控语句的外部 block 中不考虑它。

相比之下,以下几乎等效的语句是无效的,因为它打破了外部 block 约束:

if (int k=10) {
int k=20; // <===== ouch ! redefinition in the outerblock
if (k)
cout <<"oops";
}

因此,您可以拥有“that 语句的后续条件”的唯一情况是 for 语句。该标准通过用更清晰的措辞为您引用的约束提供理由来强调这种特殊情况:

6.5.3/1: (...) names declared in the for-init-statement are in the same declarative-region as those declared in the condition,

即在 init 和条件中声明相同的名称会破坏 ODR。

关于c++ - "a subsequent condition of that statement"的标准是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34497208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com