namalfernandolk
namalfernandolk

Reputation: 9134

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)

Upvotes: 58

Views: 4956

Answers (5)

Daniel
Daniel

Reputation: 28084

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.

Upvotes: 54

Brian Roach
Brian Roach

Reputation: 76908

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.

Upvotes: 73

abhi120
abhi120

Reputation: 278

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

Upvotes: 0

Ruchira Kariyawasam
Ruchira Kariyawasam

Reputation: 440

if(proceed) int i;

If we use if statement without braces it will execute only first line with the if 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.

Upvotes: 3

steffinchen
steffinchen

Reputation: 497

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

Upvotes: 12

Related Questions