bam*_*s53 39
在以下示例中,对于循环的每次迭代,所有变量都被销毁并重新创建,除了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;
}
Run Code Online (Sandbox Code Playgroud)
至于为什么; 循环实际上为它们的主体采用单个语句,只是发生了一个名为由大括号创建的复合语句的语句.在任何复合语句中创建的变量范围仅限于复合语句本身.所以这真的不是循环的特殊规则.
循环和选择语句对于作为循环或选择语句本身的一部分创建的变量有自己的规则.这些只是根据设计师认为最有用的设计而设计的.
Mik*_*sen 34
循环中声明的任何内容都限定为该循环,并且不能在花括号外部访问.实际上,您甚至不需要循环来创建新范围.你可以这样做:
{
int x = 1;
}
//x cannot be accessed here.
Run Code Online (Sandbox Code Playgroud)
Pub*_*bby 15
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
Run Code Online (Sandbox Code Playgroud)
a并且b仅在for循环的范围内可见.范围包括循环中的内容()和{}
我认为值得一提:
一些编译器可能有一个选项,它影响在for循环初始化程序中创建的变量的范围.例如,Microsoft Visual Studio有一个选项/ Zc:forScope(for Loop Scope中的强制一致性).它默认为标准c ++行为.但是,这可以更改,以便for循环变量在for循环范围之外保持活动状态.如果您使用VS,请注意此选项存在可能很有用,这样您可以确保将其设置为所需的行为.不确定是否有任何其他编译器具有此选项.
由于优化设置和" 死存储 "消除,一些编译器可能会删除它认为不必要的代码.例如,如果循环内部更改的变量未在循环外的任何位置读取,则编译器可能会丢弃循环本身.
例如,考虑以下循环:
int cnt = 0;
int trys = MAX_INT;
while (trys-- > 0)
{
cnt += trys;
}
Run Code Online (Sandbox Code Playgroud)
有些编译器可能会丢弃循环的[内容],因为循环后没有使用变量Cnt.
只想添加在for或while循环中声明的变量也在循环中作用域.例如:
for (int index = 0; index < SOME_MAX; ++index)
{
...
}
// index is out of scope here.
Run Code Online (Sandbox Code Playgroud)
int a;
for(int b=0; b<10; ++b) {
int c;
}
Run Code Online (Sandbox Code Playgroud)
范围好像是:
int a;
{
int b=0;
begin:
if (b<= 10)
{
{
int c;
}
++b;
goto begin;
}
}
Run Code Online (Sandbox Code Playgroud)
目的是使变量在明确定义的序列点超出范围.