[Solved] Inconsistency with else statements?


First off, note that if and else always apply to the single statement that follows them. You can use { } to group multiple statements into a single compound statement, but the conditional then applies to the single { ... } statement.

Consider these two equivalent statements:

if (foo) {
  bar();
}

if (foo)
  bar();

In the first the if applies to the { } block (which contains bar();) while in the second it applies directly to the bar(); statement. What may not be immediately apparent is that { } is not the only way to create a compound statement. In fact, if is another compound expression, hence it can be the direct child of another if or else statement. For instance:

if (foo)
  if (bar) {
    baz();
  }

Is perfectly valid (if hard to read) and is equivalent to:

if (foo) {
  if (bar) {
    baz();
  }
}

The same concept is true of else – whatever statement follows it will be applied if the preceding conditional is false, even if that statement is itself a compound statement!

if (foo) {
  bar();
}
else
  if (baz) {
    biff();
  }

The else applies to the whole if (baz) block, and since it’s only a single (compound) statement there’s no need for an additional { } block.

The exact grammar is specified in JLS §19, and the grammar of the different forms of the if statement are detailed in JLS §14.9. Notice that there’s no mention of else if because it’s not a formal part of the language, simply a (intentional) consequence of the grammar.


All of that said, the real reason we don’t format the code the way you’re describing is simply because it’s harder to read. It’s much simpler to think of else if as a single keyword and indent your code accordingly. Some other languages (e.g. Python) use a single keyword like elif to simplify the grammar, but it’s not really necessary.

8

solved Inconsistency with else statements?