7
if ( year % 4 == 0 )
    int i = 0;
else
    int j = 0;

The syntax errors which crop up in eclipse due to this line of code are:

  • Syntax error on token "int", delete this token
  • i cannot be resolved to a variable
  • Syntax error on token "int", delete this token
  • j cannot be resolved to a variable
  • Syntax error on token "=", delete this token

I have no clue why this is happening.

From what I have observed, I think putting an int declaration in the if else construct body is making it happen.

If i declare i and j earlier in the code and the run the program then the error vanishes like:

int i; int j;
if ( year % 4 == 0 )
    i = 0;
else
    j = 0;

No syntax error in this case. Why?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
arpansen
  • 205
  • 1
  • 13
  • 3
    I was writing an answer; but since its closed I can't. Look at the JLS for [the if statement](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.9), if you go up you'll see that a `LocalVariableDeclarationStatement` can only be in a `Block` – Alexis C. Dec 04 '14 at 22:30

1 Answers1

0

It is probably because of scope. Declaring i and j inside of the if makes them unreachable outside of the if statement. Declaring them outside changes their scope.

zack.lore
  • 527
  • 5
  • 10