在条件中声明变量而没有花括号时编译器错误 [英] Compiler error when declaring a variable inside if condition and no curly braces
问题描述
为什么第一个如果
编译好,第二个失败?
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)
推荐答案
因为语言规范如此:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html
声明将实体引入程序并包含可在名称中用于引用此实体的标识符(第3.8节)。声明的实体是以下之一:
...
一个局部变量,以下之一:
*在块中声明的局部变量(§14.4)
*在for语句中声明的局部变量(§14.14)
A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity. A declared entity is one of the following:
...
A local variable, one of the following:
* A local variable declared in a block (§14.4)
* A local variable declared in a for statement (§14.14)
您的第一个示例是在块内声明 i
(用花括号表示)。你的第二个不是,语句也不是。
Your first example is declaring i
inside a block (denoted by curly braces). Your second isn't, nor is it a for
statement.
编辑添加:强>这只会让公众有意义。如果它被允许,那将是无用的。它会立即超出范围。
Edited to add: Which just makes commons sense. If it were allowed, it would be useless. It would immediately fall out of scope.
这篇关于在条件中声明变量而没有花括号时编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!