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

查看:16
本文介绍了为什么我不能以这种方式在 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,因为在 for 循环中不能有另一个语句.基本上在那个地方的新变量声明将超出下一个语句的范围,因此没有任何好处.

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天全站免登陆