C++ “while”和“for”循环的范围是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7880658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the scope of a 'while' and 'for' loop?
提问by T.T.T.
What is the scope of a while
and for
loop?
while
andfor
循环的范围是什么?
For example, if I declared an object within the loop, what is its behavior and why?
例如,如果我在循环中声明了一个对象,它的行为是什么,为什么?
采纳答案by bames53
In the following examples all the variables are destroyed and recreated for each iteration of the loop except i
, which persists between loop iterations and is available to the conditional and final expressions in the for loop. None of the variables are available outside the loops. Destruction of the variables inside the for loop body occurs before i
is incremented.
在以下示例中,所有变量都会为循环的每次迭代销毁并重新创建,除了i
,它在循环迭代之间持续存在并且可用于 for 循环中的条件表达式和最终表达式。在循环之外没有任何变量可用。for 循环体内的变量的销毁发生在i
递增之前。
while(int a = foo()) {
int b = a+1;
}
for(int i=0;
i<10; // conditional expression has access to i
++i) // final expression has access to i
{
int j = 2*i;
}
As for why; loops actually take a single statement for their body, it just happens that there's a statement called a compound statement created by curly braces. The scope of variables created in any compound statement is limited to the compound statement itself. So this really isn't a special rule for loops.
至于为什么;循环实际上为它们的主体采用单个语句,只是碰巧有一个称为复合语句的语句,由花括号创建。在任何复合语句中创建的变量范围仅限于复合语句本身。所以这真的不是循环的特殊规则。
Loops and selection statements do have their own rules for the variables created as a part of the loop or selection statement itself. These are just designed according to whatever the designer felt was most useful.
对于作为循环或选择语句本身的一部分创建的变量,循环和选择语句确实有自己的规则。这些只是根据设计师认为最有用的东西设计的。
回答by Mike Christensen
Anything declared in the loop is scoped to that loop and cannot be accessed outside the curly braces. In fact, you don't even need a loop to create a new scope. You can do something like:
循环中声明的任何内容都限定在该循环内,不能在花括号外访问。事实上,您甚至不需要循环来创建新的作用域。您可以执行以下操作:
{
int x = 1;
}
//x cannot be accessed here.
回答by Pubby
int d;
// can use d before the loop
for(int a = 0; a < 5; ++a) // can use a or d in the ()
{
int b;
// can use d, a, b in the {}
}
int c;
// can use d, c after the loop
a
and b
are only visible in the scope of the for loop. The scope includes what's in the loops ()
and {}
a
并且b
仅在 for 循环范围内可见。范围包括循环中的内容()
和{}
回答by Ed N.
I thought it would be worth mentioning:
我认为值得一提的是:
Some compilers may have an option which effects the scope of variables created within the for loop initializer. For example, Microsoft Visual Studio has an option /Zc:forScope(Force Conformance in for Loop Scope). It defaults to standard c++ behavior. However, this can be changed so that the for loop variable is kept alive outside the for loop scope. If you are using VS it might be useful to be aware that this option exists so you can make sure its set to the desired behavior. Not sure if there are any other compilers which have this option.
一些编译器可能有一个选项来影响在 for 循环初始值设定项中创建的变量的范围。例如,Microsoft Visual Studio 有一个选项/Zc:forScope(ForLoop Scope 中的强制一致性)。它默认为标准 C++ 行为。但是,这可以更改,以便 for 循环变量在 for 循环范围之外保持活动状态。如果您正在使用 VS,了解此选项的存在可能会很有用,这样您就可以确保将其设置为所需的行为。不确定是否有任何其他编译器具有此选项。
Some compilers may eliminate code it thinks is unnecessary, due to optimization settings and "Dead Store" elimination. For example, if the variable being changed inside the loop isn't read anywhere outside the loop, the loop itself may be discarded by the compiler.
由于优化设置和“死存储”消除,一些编译器可能会消除它认为不必要的代码。例如,如果在循环内更改的变量没有在循环外的任何地方读取,则编译器可能会丢弃循环本身。
For example, consider the following loop:
例如,考虑以下循环:
int cnt = 0;
int trys = MAX_INT;
while (trys-- > 0)
{
cnt += trys;
}
it is possible that some compilers may discard [the contents of] the loop, because the variable Cnt isn't being used after the loop.
有些编译器可能会丢弃循环的[内容],因为在循环之后没有使用变量 Cnt。
回答by Lou
Just wanted to add that variables declared in the for or while loop are also scoped within the loop. For example:
只是想添加在 for 或 while 循环中声明的变量也在循环内。例如:
for (int index = 0; index < SOME_MAX; ++index)
{
...
}
// index is out of scope here.
回答by Mooing Duck
int a;
for(int b=0; b<10; ++b) {
int c;
}
scopes as if it were:
范围就好像它是:
int a;
{
int b=0;
begin:
if (b<= 10)
{
{
int c;
}
++b;
goto begin;
}
}
The purpose is so that variables go out of scope at clearly defined sequence points.
目的是使变量在明确定义的序列点超出范围。
回答by John Dibling
for( int i = 0; i < 10; ++i )
{
string f = "foo";
cout << f << "\n";
}
// i and f are both "gone" now
In the above sample code, both i
and f
are scoped within the {
{ and }
} When the closing brace is executed, both variables fall out of scope.
在上面的示例代码中,i
和f
都在{
{ 和}
}范围内,当执行右大括号时,两个变量都超出了范围。
The reason for this is simply that the Standard says so; that's how the C++ language works.
原因很简单,标准是这么说的;这就是 C++ 语言的工作原理。
As for motivation, consider that this can be used to your advantage:
至于动力,请考虑这可以用于您的优势:
for( ...)
{
std::auto_ptr<SomeExpensiveObject> obj(new SomeExpensiveObject);
}
In the above code, we are using an RAII smart pointer to "own" the expensive object we created within the loop. The scoping semantics of the for
loop dictate that after each execution of the loop, the object that was created during that iteration will be destroyed.
在上面的代码中,我们使用 RAII 智能指针来“拥有”我们在循环中创建的昂贵对象。for
循环的范围语义规定,在每次执行循环后,在该迭代期间创建的对象将被销毁。
回答by Dipan Mehta
Check out this code
看看这个代码
#include < stdio.h >
int i = 10;
int main() {
for(int i=0; i<3; i++) {
fprintf(stdout," for i = %d & upper i = %d\n",i,::i);
}
while (i>3) {
int i = 30;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
i++;
fprintf(stdout," while i = %d & upper i = %d\n",i,::i);
}
fprintf(stdout,"i = %d \n",i);
}
In the code above, the global variable iis different from one which is controlling the for loop.
在上面的代码中,全局变量i与控制 for 循环的变量不同。
It will print
它会打印
for i = 0 & upper i = 10
for i = 1 & upper i = 10
for i = 2 & upper i = 10
when while loop is executed - the variable idefined inside while is having local scope, where as the variable under (i > 3)follows the global variable, and doesn't refer to local scope.
执行 while 循环时 -我在 while 中定义的变量具有局部作用域,其中(i > 3)下的变量跟随全局变量,并且不引用局部作用域。
Dipan.
地盘。
回答by MGZero
The variable is within the scope of the loop. I.e. you need to be within the loop to access it. It's the same as if you declared a variable within a function, only things in the function have access to it.
变量在循环的范围内。即您需要在循环内才能访问它。就像你在函数中声明了一个变量一样,只有函数中的东西才能访问它。
回答by JoeFish
In C/C++, the scope of a variable declared in a for or while loop (or any other bracketed block, for that matter) is from the open bracket to the close bracket.
在 C/C++ 中,在 for 或 while 循环(或任何其他带括号的块,就此而言)中声明的变量的范围是从左括号到右括号。
while (some_condition == true)
{
int myVar = 3;
}
cout << myVar << endl; // This will cause a compilation error