阅读 http://en.cppreference.com/w/cpp/language/for我发现,for
循环的 condition 部分可以是表达式,可以根据上下文转换为 bool
,也可以是 单变量声明强制大括号或等于初始值设定项(6.4/1 中的语法规范):
condition:
- expression
- type-specifier-seq declarator = assignment-expression
但我从未在源代码中看到过后者的使用。
什么在 for
循环语句的 condition 部分使用变量声明是有利可图的(在简洁性、表现力、可读性方面) ?
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
在 condition 中声明的变量只能在整个生命周期(范围)内转换为 true
如果没有副作用影响转换为 bool 的结果
。
我只能想象几个用例:
- 声明一个类类型的变量,具有用户定义的
operator bool
。 某种改变循环变量的 cv-ref-qualifiers:
for (int i = 5; int const & j = i; --i) { // using of j }
但两者都非常人为。
最佳答案
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);
}
这些语句将它们需要的所有变量保留在尽可能小的范围内。如果语句内不允许声明形式,则需要在语句外声明一个变量,但只在语句执行期间需要它。这意味着你要么泄漏到太大的范围,要么你需要难看的额外范围。允许语句内的声明提供了一种方便的语法,虽然它很少有用,但当有用时,这非常好。
也许最常见的用例是在像这样的多重分派(dispatch)情况下:
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
语句允许条件为假的情况的代码路径,在可选的 else
block 中给出。 while
和 for
都不允许您以这种方式使用 bool 检查的结果,即没有 for ... else
或 while ... else
语言中的结构。
关于c++ - 在 FOR 循环语句的条件部分使用声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35453272/