nam*_*olk 57 java if-statement declaration block
为什么第一次if编译好,第二次失败?
if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)
Run Code Online (Sandbox Code Playgroud)
Bri*_*ach 72
因为语言规范如此说:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html
声明将实体引入程序,并包含可在名称中用于引用此实体的标识符(第3.8节).声明的实体是以下之一:
...
局部变量,以下之一:
*在块中声明的局部变量(第14.4节)
*在for语句中声明的局部变量(第14.14节)
你的第一个例子是i在一个块内声明(用花括号表示).你的第二个不是,也不是一个for声明.
编辑添加:这只是让公共感觉.如果它被允许,那将是无用的.它会立即超出范围.
Dan*_*iel 53
来自Java语言规范.
Block:
{ BlockStatementsopt }
BlockStatements:
BlockStatement
BlockStatements BlockStatement
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
和
IfThenStatement:
if ( Expression ) Statement
这似乎int i是一个LocalVariableDeclarationStatement,而不是一个Statement.所以它不起作用.
ste*_*hen 12
这是因为它不是有用的代码.如果你有一个没有花括号({})的if语句,那么只执行if之后的第一行/语句.因此,如果您只声明一个局部变量,则不能在其他任何地方使用它.因此宣布它绝对是多余的.
if(proceed){
int i= 0;
// variable i can be used here
//...
}
if (proceed) int i; // i can not be used anywhere as it is a local variable
Run Code Online (Sandbox Code Playgroud)