以下语法有效:
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-list2 The rules for conditions apply both to selection-statements and to the
for
andwhile
statements (6.5). [...]
和第 6.5 节
1 Iteration statements specify looping.
iteration-statement:while
( condition ) statementdo
statementwhile
( 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/