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

标签 c++ language-lawyer

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/

相关文章:

c++ - 类模板的友元函数是否应该成为所有实例化的友元?

c++ - cppreference 中的哪一部分告诉我结构化绑定(bind)声明仅适用于编译时已知对象?

c++ - C++ 中的日期/时间解析(任何格式字符串到 Epoch)

c++ - 复制构造函数被调用了多少次?

c++ - 对于 C++14 中不确定值和未定义行为的使用,C++ 标准是否发生了变化?

c++ - 是否调用函数指针来生成代码未定义的行为?

C++ 将文本文件读入 vector < vector >,然后根据内部 vector 中的第一个单词写入 vector 或数组

c++ - cmake add_custom_command 失败,目标被删除

c++ - 为什么创建一个由不同进程共享的环形缓冲区如此困难(在 C++ 中),我做错了什么?

c++ - 我认为这是 C++11 标准中的一个(小)缺陷