c++ - 为什么不能在 do while 循环的表达式部分声明变量?

标签 c++ declaration do-while

以下语法有效:

while (int i = get_data())
{
}

但以下不是:

do
{
} while (int i = get_data());

我们可以通过标准草案N4140部分6.4了解原因:

1 [...]

condition:
     expression
     attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
     attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

2 The rules for conditions apply both to selection-statements and to the for and while statements (6.5). [...]

和第 6.5 节

1 Iteration statements specify looping.

      iteration-statement: 
             while ( condition ) statement
             do statement while ( expression ) ;

相反,你被迫做一些丑陋的事情,比如:

int i = get_data();
do
{
} while ((i = get_data())); // double parentheses sic

这样做的理由是什么?

最佳答案

范围界定似乎是个问题,在 do while 语句的 while 部分中声明的 i 的范围是什么?当声明实际上低于循环本身时,在循环中提供一个变量似乎是相当不自然的。其他循环没有这个问题,因为声明在循环体之前。

如果我们查看 draft C++ standard栏目[stmt.while]p2我们看到对于 while 语句:

while (T t = x) statement

相当于:

label:
{ // start of condition scope
    T t = x;
    if (t) {
        statement
    goto label;
    }
} // end of condition scope

和:

The variable created in a condition is destroyed and created with each iteration of the loop.

对于 do while 的情况,我们将如何表述这一点?

正如 cdhowie 指出的,如果我们看一下 [stmt.do]p2 部分它说(强调我的):

In the do statement the substatement is executed repeatedly until the value of the expression becomes false. The test takes place after each execution of the statement.

这意味着循环体在我们到达声明之前就被评估了。

虽然我们可以为这种情况创建一个异常(exception),但它违反了我们的直觉,即一般来说,一个名称的声明点是在我们看到完整的声明之后(有一些异常(exception),例如类成员变量) 具有不明确的好处。 声明点3.3.2部分中介绍。

关于c++ - 为什么不能在 do while 循环的表达式部分声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27430640/

相关文章:

c++ - 提升用户输入功能的测试用例

c++ - std::string 分配的内存是否会影响性能?

C 语言中可以使用 scanf() 来声明变量吗?

c#:(静态)类级变量

vb.net - 为什么VB.NET中这个类有参数?

c - 哪种代码更简洁、设计更好?

java - 这个Java猜谜游戏程序中嵌套的do-while循环的作用是什么?

c++ - 在另一个 .cpp 文件中访问一个 .cpp 文件中定义的全局变量

javascript - 如何使用javascript计算数字中的特定数字

c++ - 如何创建动态大小的链表数组?