问题描述
我们经常需要这样的循环
More often than not we need loops like this
do
{
Type value(GetCurrentValue());
Process(value);
}while(condition(value));
不幸的是,这不会编译,因为 value
的范围以}
结尾。
Unfortunately this will not compile, because value
's scope ends at }
. Which means that I will have to declare it outside the loop.
Type value;
do
{
value = GetCurrentValue();
Process(value);
}while(condition(value));
我不喜欢这样做至少有两个原因。首先,我喜欢在本地声明。其次,如果值不是可分配的或默认可构造的,而只能是副本可构造的,则这是一个问题。
I don't like this for at least two reasons. For one, I like declaring things locally. And second, this is a problem if value is not assignable or default-constructible, but only copy-constructible.
因此,我的问题有两个方面。首先,我想知道将do while的范围扩展到最终条件是否有特殊原因/困难(就像在for循环中声明的变量的范围包括for循环的主体一样,尽管它实际上是大括号之外)。而且,如果您相信我第一个问题的答案是就是这样。不要问为什么要问。那么我想知道是否有成语可以帮助编写do-while循环,类似于我的示例,但没有我提到的缺点。
So, my question has two sides. First, I'd like to know if there was a particular reason/difficulty in extending the do while's scope to the final condition as well (just as the scope of variables declared in for loop includes the body of the for loop despite it physically being outside of the braces). And if you believe that the answer to my first question is "It's just the way it is. Don't ask why questions." then I'd like to know if there are idioms that can help write do-while loops similar to the ones in my example but without the downsides I mentioned.
希望问题很清楚。
推荐答案
如果希望将值
保留在while循环的本地范围内,您可以改为执行以下操作:
If you'd like to keep value
locally scoped for the while loop, you can do this instead:
do
{
Type value(GetCurrentValue());
Process(value);
if (! condition(value) )
break;
} while(true);
这只是个人喜好,但我发现而
循环的结构如下所示( while
而不是 do-while
):
This is just personal preference, but I find while
loops structured like the following more readable (while
instead of do-while
):
while(true) {
Type value(GetCurrentValue());
Process(value);
if (! condition(value) ) {
break;
}
}
C / C ++中的作用域规则如下:在大括号 {...}
块内声明的局部变量是本地的,仅对该块可见。例如:
The scoping rules in C/C++ works as follows: Local variables declared within a brace {...}
block is local / visible only to that block. For example:
int a = 1;
int b = 2;
{
int c = 3;
}
std::cout << a;
std::cout << b;
std::cout << c;
会抱怨未声明 c
。
关于基本原理-只是保持一致性,这就是语言的定义方式
As for rationale - it's just a matter of consistency and "that's just how the language is defined"
这篇关于为什么while条件不在do while范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!