为什么不能以这种方式在一个for循环中定义一个变量? [英] Why can't I define a variable inside a for loop in this way?

查看:554
本文介绍了为什么不能以这种方式在一个for循环中定义一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过测试我发现,

这是不合法的:

for (int i= 0; i < 1000000000; i++) 
    int j = i & i+1 ; // j cannot be declared here!

但这是:

for (int i= 0; i < 1000000000; i++) { 
    int j = i & i+1 ;
}

为什么?

推荐答案

第一种方式是不合法的,因为编译器很清楚你不能使用 j 因为你不能在中有另一个语句用于循环。基本上,在那个地方的新的变量声明将超出下一个语句的范围,因此没有任何好处。

The first way is not legal, as it is clear to the compiler that you can't use j that you declared there, as you can't have another statement inside that for loop. Basically the new declaration of variable at that place will go out of scope the very next statement, thus is not doing any good.

在第二种情况下,循环是后跟大括号,它创建一个新范围,您可以使用该变量。

While in the second case, the loop is followed by braces, which creates a new scope, and you can use the variable.

这篇关于为什么不能以这种方式在一个for循环中定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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