以下语法有效:
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 条件规则同时适用于选择语句和
到for
and while
声明(6.5)。 [...]
和部分6.5
1 迭代语句指定循环。
iteration-statement:
while
( condition ) statement
do
statement while
( expression ) ;
相反,你被迫做一些丑陋的事情,比如:
int i = get_data();
do
{
} while ((i = get_data())); // double parentheses sic
这样做的理由是什么?
范围界定似乎是个问题,范围是什么i
声明于while
的一部分do while
陈述?当声明实际上位于循环本身下方时,在循环中使用变量似乎很不自然。对于其他循环,您不会遇到此问题,因为声明位于循环体之前。
如果我们看一下C++ 标准草案 https://github.com/cplusplus/draft/blob/master/papers/n4140.pdf部分[stmt.while]p2 https://timsong-cpp.github.io/cppwp/n4140/stmt.while#2我们看到对于while 语句 that:
while (T t = x) statement
相当于:
label:
{ // start of condition scope
T t = x;
if (t) {
statement
goto label;
}
} // end of condition scope
and:
在条件中创建的变量将在循环的每次迭代中被销毁和创建。
我们将如何制定这个do while
case?
正如 cdhowie 指出的,如果我们看一下部分[stmt.do]p2 https://timsong-cpp.github.io/cppwp/n4140/stmt.do#2它说 (强调我的):
在 do 语句中,子语句被重复执行,直到
表达式的值变为 false。测试在每次之后进行
语句的执行。
这意味着循环体在我们到达声明之前就被评估了。
虽然我们可以为这种情况创建一个例外,但这会违反我们的直觉,即通常名称的声明点是在我们看到完整的声明之后(有一些例外,例如类成员变量)带来的好处不明确。申报点已在章节中介绍3.3.2
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)