读http://en.cppreference.com/w/cpp/language/for我发现,即条件 for
环的一部分可以是表达,上下文转换为bool
,或单变量 - 使用强制括号或相等初始化程序的声明(6.4 / 1中的语法规范):
条件:
- 表达
- type-specifier-seq declarator = assignment-expression
但我从来没有在源代码中看到过使用后者。
什么在for
循环语句的条件部分中使用变量声明是有利可图的(在简洁性,表达性,可读性方面)吗
for (int i = 0; bool b = i < 5; ++i) {
// `b` is always convertible to `true` until the end of its scope
} // scope of `i` and `b` ends here
在条件中声明的变量只能在整个生命周期(范围)内转换为true
,如果没有影响转换为bool
的结果的副作用。< / p>
我只能想象几个用例:
operator bool
。某种改变循环变量的cv-ref-qualifiers:
for (int i = 5; int const & j = i; --i) {
// using of j
}
但他们都非常有艺术性。
答案 0 :(得分:8)
可以以类似的方式使用所有三个语句if
,for
和while
。为什么这有用?有时它只是。考虑一下:
Record * GetNextRecord(); // returns null when no more records
Record * GetNextRecordEx(int *); // as above, but also store signal number
// Process one
if (Record * r = GetNextRecord()) { process(*r); }
// Process all
while (Record * r = GetNextRecord()) { process(*r); }
// Process all and also keep some loop-local state
for (int n; Record * r = GetNextRecordEx(&n); )
{
process(*r);
notify(n);
}
这些语句在尽可能小的范围内保留所需的所有变量。如果语句中不允许声明表单,则需要在语句外声明一个变量,但在语句的持续时间内只需要它。这意味着你要么泄漏到太大的范围,要么你需要难看的额外范围。允许声明中的声明提供了一个方便的语法,虽然很少有用,但 时很有用。
也许最常见的用例是这样的多分派演员情况:
if (Der1 * p = dynamic_cast<Der1 *>(target)) visit(*p);
else if (Der2 * p = dynamic_cast<Der2 *>(target)) visit(*p);
else if (Der3 * p = dynamic_cast<Der3 *>(target)) visit(*p);
else throw BadDispatch();
暂且不说:只有if
语句允许条件为false的情况的代码路径,在可选的else
块中给出。 while
和for
都不允许您以这种方式使用布尔检查的结果,即语言中没有for ... else
或while ... else
构造。