局部变量的范围增强for循环 [英] scope of local variable in enhanced for-loop

查看:163
本文介绍了局部变量的范围增强for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对变量范围有一个相当简单的问题。

我对增强型For-Loops很熟悉,但是我不明白为什么要声明一个新的变量来保存每个元素。一个例子可能会澄清我的问题:

  int [] ar = {1,2,3}; 
int i = 0;
for(i:ar){//如果我不声明一个新变量,则会导致错误:int i
// for(int i:ar)// this fine fine
的System.out.println(ⅰ);





$ b为什么我要声明这个新的变量?毕竟 i 在for循环中是可访问的。我不想使用任何以前的值 i ,只是不想声明一个新的变量。 (我猜其他可迭代的项目,它可能会更快使用相同的变量)。

我想这是如何建立增强的For-Loops,但不会破坏整个范围理念?

从上述行为出现了一个问题。无论编译器对整个 for 循环使用相同的变量,只是更新它的值或者创建一个新的变量每次迭代?



一个有趣的部分是,如果我同时声明 int i 之前和之内
lockquote

重复局部变量i


这使得(至少对我而言)更加奇怪。所以我不能在循环中使用之前声明的变量 i 作为循环,但是我也不能在其中声明一个新变量

解决方案


那为什么我要声明这个新的变量?


因为这是定义语法的方式。


毕竟我可以在for循环中访问。

这就是语义。这与语法无关。


我不想使用以前的任何值,只是不想声明一个新的变量。 (我猜其他可迭代的项目,它可能会更快使用相同的变量)。

不要猜测性能。测试和测量。但在这种情况下,没有什么可衡量的,因为任何工作代码比任何非工作代码都快。


I have a rather simple question about variable scope.

I am familiar with the Enhanced For-Loops but I do not get why I should declare a new variable to keep each element. One example might clarify my question:

        int[] ar = {1, 2, 3};
        int i = 0;
        for(i : ar) {  // this causes an error if I do not declare a new variable: int i
//        for(int i : ar) // this works fine
            System.out.println(i);
        }

So why I should declare this new variable? After all i is accessible inside the for loop. I did not want to use any previous value of i, just did not want to declare a new variable. (I guessed for other iterable items it might be faster using the same variable).

I guess that's how Enhanced For-Loops were built but does not this break the whole scope idea?

There is a question rising from the above behavior. Whether the compiler uses the same variable for the whole for loop and just updates its value or it creates a new variable for each iteration?

An interesting part is that if I keep both declaration of int i (before and inside the for loop) I even get a compiler error about

Duplicate local variable i

which makes (at least for me) things a bit more strange. So I cannot use the previous declared variable i inside the for loop but neither can I declare a new one inside it with the same name.

解决方案

So why I should declare this new variable?

Because that's the way the syntax is defined.

After all i is accessible inside the for loop.

That's semantics. It's irrelevant to syntax.

I did not want to use any previous value of i, just did not want to declare a new variable. (I guessed for other iterable items it might be faster using the same variable).

Don 't guess about performance. Test and measure. But in this case there's nothing to measure, because any working code is faster than any non-working code.

这篇关于局部变量的范围增强for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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