Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 576
namalfernandolk Avatar asked Feb 09 '12 06:02

namalfernandolk


4 Answers

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.

like image 63
Brian Roach Avatar answered Oct 16 '22 07:10

Brian Roach


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.

like image 21
Daniel Avatar answered Oct 16 '22 07:10

Daniel


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
like image 36
steffinchen Avatar answered Oct 16 '22 06:10

steffinchen


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.

like image 45
Ruchira Kariyawasam Avatar answered Oct 16 '22 06:10

Ruchira Kariyawasam