什么是的',而'和'for'循环范围有多大? [英] What is the scope of a 'while' and 'for' loop?

查看:79
本文介绍了什么是的',而'和'for'循环范围有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是,而循环的范围有多大?

What is the scope of a while and for loop?

例如,如果我宣布在循环中的一个对象,什么是它的行为,为什么?

For example, if I declared an object within the loop, what is its behavior and why?

推荐答案

在下面的例子中所有的变量都破坏并重新创建了循环的每个迭代除了 I ,其中循环迭代之间依然存在,并提供给有条件的,最终的前pressions在for循环。的变量没有可用的环外。里面的变量的循环体的破坏之前我发生递增。

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.

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.

这篇关于什么是的',而'和'for'循环范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆