They do this to avoid the dangling else problem.
In many programming languages, the syntax for else-if statements is ambiguous. For example, consider the following C program:
if(a) if (b) x++; else y++;
Which if
should the else belong to? Is it the inner one?
if (a)
if (b)
x++;
else
y++;
or the outer one?
if (a)
if (b)
x++;
else
y++;
This ambiguity is known as the "dangling else problem". One way that programming languages can avoid it is to require delimiters around the "then" and the "else" part of the if
. Some languages, such as Swift, mandate that there must be curly braces:
if (a) {
x++;
} else {
y++;
}
Some languages instead use then
and end
keywords, for a similar effect. For example, Lua:
if a then
x = x + 1
else
y = y + 1
end
However, if our language requires these delimiters around the else
then we cannot write else if
as we do in C. Because else
must be followed by an open curly brace, we would end up with open braces between the else
and the if
, and a long sequence of closing delimiters at the end.
if (a) {
x++;
} else { if (b) {
y++;
} else { if (c) {
z++;
} else {
w++;
}}} /*ouch!*/
Having an elseif
keyword is an elegant way to avoid this }}}
avalanche. We can still mandate braces after if
and else
, but there aren't those pesky braces between the two
Some languages such asSwift and Rust avoid the else { if
problem by special casing the else if
. Their grammar says that the next token after the else
must be a {
, unless it's an if
. This is certainly a valid way to solve the problem and avoids creating a new keyword. That said, the programmer must be aware that else if
is a special case. If one is used to languages with traditional if-else syntax, they might expect they are allowed to write to substitute any other statement in place of the if
statement in the else if
. In languages with elseif
this question doesn't come up because it's loud and clear that elseif
is special.