在 if 条件内声明变量并且没有花括号时出现编译器错误
为什么第一个 if
编译良好而第二个失败?
if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)
Why does this first if
compile well and the second fail?
if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为语言规范是这样说的:
http://docs.oracle.com/javase /specs/jls/se7/html/jls-6.html
您的第一个示例是在块内声明
i
(用大括号表示)。你的第二个不是,也不是for
语句。编辑添加:这符合常识。如果允许的话,那就没什么用了。它会立即超出范围。
Because the language spec says so:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html
Your first example is declaring
i
inside a block (denoted by curly braces). Your second isn't, nor is it afor
statement.Edited to add: Which just makes commons sense. If it were allowed, it would be useless. It would immediately fall out of scope.
来自 Java 语言规范。
并且
似乎
int i
是一个LocalVariableDeclarationStatement
,而不是Statement
。所以这是行不通的。From the Java Language Spec.
and
It seems that
int i
is aLocalVariableDeclarationStatement
, not aStatement
. So it doesn't work.这是因为它不会是有用的代码。
如果您的 if 语句不带大括号 ({}),则仅执行 if 之后的第一行/语句。所以如果你只声明一个局部变量,它就不能在其他地方使用。所以宣布它绝对是多余的。
This is because it would not be useful code.
If you have an if-statement without curly braces ({}), only the first line / statement after the if is executed. So if you only declare a local variable, it cannot be used anywhere else. So declaring it is absolutely superfluous.
if(继续) int i;
如果我们使用不带大括号的
if
语句,它将仅以条件方式执行带有if
的第一行。其他行将正常执行。这是编译失败,因为局部变量声明以条件方式发生,并且编译器认为使用 false 语句无法访问它。
如果使用花括号,则变量声明和块内局部变量的使用,因此编译器假定它是可访问的代码。然后就没有编译器错误了。
if(proceed) int i;
If we use
if
statement without braces it will execute only first line with theif
for the conditional manner. Other lines will execute normally.This is compilation fail, because local variable declaration happen with conditional manner and compiler assume it is not reachable with the false statement.
If you use a curly braces, then variable declaration and use of local variable within the block and hence compiler assume it is reachable code. Then no compiler errors.
就像在 Java / C++ 中一样,如果我们编写不带大括号的 if ,则仅执行第一个语句
在这种情况下,变量 i 没有用。你在 if 语句中声明它,它的作用域在此语句之后结束,这是无用的。
在 C++ 中,这是允许的,但 Java 不允许这样做
As in Java / C++ ,if we write if without braces ,only 1st statement is executed
In this case , variable i is of no use. You are declaring it in if statement and its scope ends after this statement , which is useless
In C++ , this is allowed ,but Java doesn't allow this