Compiler error when declaring a variable inside if condition and no curly braces

为什么这个第一if编译阱和第二失败?

if(proceed) {int i;} // This compiles fine.
if(proceed) int i;// This gives an error. (Syntax error on token ")", { expected after this token)

Because the language spec says so:

http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html

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)

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.


From the Java Language Spec.

    Block:
            { BlockStatementsopt }

    BlockStatements:
            BlockStatement
            BlockStatements BlockStatement

    BlockStatement:
            LocalVariableDeclarationStatement
            ClassDeclaration
            Statement

and

    IfThenStatement:
            if ( Expression ) Statement

It seems that int i is a LocalVariableDeclarationStatement , not a Statement . So it doesn't work.


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(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
链接地址: http://www.djcxy.com/p/10198.html

上一篇: 替换被特定标记包围的字符UNLESS

下一篇: 如果条件和大括号中没有声明变量,编译器会报错