在for循环中声明变量的优缺点?

我的 -

在for循环中声明变量有什么优点和缺点?我想改变我的讲师的想法,或者改变我的观点:讲师强迫我使用:

// Declare variables
int i;
...

for(i = 0; boolen expesion; update)   // Note i not declared here

我喜欢做:

for(int i = 0; boolean expesion; update)   // Note i is declared here

在考试中,这是按照我的方式做的惩罚。.我试图告诉他:

  • 我没有看到代码做他的方式。
  • 它不是那个重要的变量,所以使其局部有意义。
  • 它可能是一个情况是在循环中,您可能需要使用long类型变量。

他的回答是:“如果这里有几个循环,则无需重复声明相同的变量”。很难与讲师争论如此特殊,因为您是来自新兴国家的一年级学生。但是int并不会占用太多内存,而Java拥有垃圾回收器可以清理内存。

因此,请帮我用一个好的论据说服他或我。

安德烈亚斯

他是对的,您不需要重复声明相同的变量,但是:

  • 优良作法是将变量的范围限制在使用它们的位置。

  • 声明变量分别实际上需要的源代码的一个多个线路,所以它不是减少代码本身。

  • 在每个for循环中声明变量不会占用更多空间。

  • 生成的字节码相同。

所以,如果你不需要的变量for循环,你应该总是声明变量的范围for循环。帮助防止意外将变量用于其他目的。

让我们以下面的代码:

static void test1() {
    int i;
    for (i = 0; i < 10; i++)
        ;
    for (i = 0; i < 10; i++)
        ;
}
static void test2() {
    for (int i = 0; i < 10; i++)
        ;
    for (int i = 0; i < 10; i++)
        ;
}

如您所见,分别声明i需要多一行代码。

字节码是这样的:

static void test1();               static void test2();
  Code:                              Code:
     0: iconst_0                        0: iconst_0
     1: istore_0                        1: istore_0
     2: goto          8                 2: goto          8
     5: iinc          0, 1              5: iinc          0, 1
     8: iload_0                         8: iload_0
     9: bipush        10                9: bipush        10
    11: if_icmplt     5                11: if_icmplt     5
    14: iconst_0                       14: iconst_0
    15: istore_0                       15: istore_0
    16: goto          22               16: goto          22
    19: iinc          0, 1             19: iinc          0, 1
    22: iload_0                        22: iload_0
    23: bipush        10               23: bipush        10
    25: if_icmplt     19               25: if_icmplt     19
    28: return                         28: return

如您所见,它们是完全相同的,因此它们在栈上为局部变量使用相同数量的空间。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章