<p>In C, <code>else if</code> is nothing but a new <code>if</code> statement after a single-statement <code>else</code> clause. Why do languages like Python and Ruby have a dedicated construct for <code>elsif</code>/<code>elif</code>?</p>

<syntax><language-comparison>
Why do some PL choose to have a dedicated keyword for elseif instead of like in C?
<h1>They need one</h1>
<p>In C-style languages like JS, you can put a single statement after an <code>if</code> to run just that one:</p>
<pre><code>if (x == 1) print(&quot;x is 1!&quot;);
</code></pre>
<p>In fact, <code>else if</code> isn't even necessarily interpreted specially by the compiler. It could just be parsed as an <code>if</code> statement directly following the <code>else</code>.</p>
<p>However, in languages like Python where you can't do this, it would be natural to have a keyword specifically for else-if since you don't get that for free.</p>

CC BY-SA 4.0
2023-05-16T17:20:34.930Z
2023-05-16T17:20:34.930Z
rydwolf
CC BY-SA 4.0
2023-05-16T17:25:44.210Z
There are languages that have "else if" as separate words but do not allow a single expression after `if` (like Rust)
mousetail 'he-him'
CC BY-SA 4.0
2023-05-16T18:06:29.803Z
@mousetail That's true, I was going to touch on how it's possible to detect an `else if` even without that, might come back and do that in a sec
rydwolf
<p>The way the chaining of <code>else if</code> blocks is defined in C follows naturally from the way the grammar allows for braceless blocks:</p>
<pre><code>if (x) {
} else if (y) {
}
</code></pre>
<p>being parsed the same as</p>
<pre><code>if (x) {
} else
    if (y) {
    }
</code></pre>
<p>i.e.</p>
<pre><code>if (x) {
} else {
    if (y) {
    }
}
</code></pre>
<p>When you allow for such constructs in the syntax, a dedicated keyword is useless.</p>
<p>On the other hand, if you take Python, for example, since blocks are defined by indentation (and not by enclosing tokens such as braces), this is not valid out-of-the-box (you have to special-case it, whereas in C it was &quot;free&quot;):</p>
<pre><code>if x:
    pass
else if y:
    pass
</code></pre>
<p>So, given that we're forced to create that special case, it makes sense to choose something shorter than <code>else if</code>, hence <code>elif</code> (or <code>elsif</code>).</p>

CC BY-SA 4.0
2023-05-16T17:24:57.357Z
2023-05-16T22:38:18.470Z
2023-05-16T22:38:18.470Z
zdimension
<p>Another reason for <code>elseif/elsif/elif</code> is if the conditional construct has a keyword terminator, like the shell's <code>fi</code> or Lua's <code>end</code>.  You don't want to be writing <code>else if</code> because now you're writing nested <code>if</code>'s, which have to be terminated with a whole sequence of repeated <code>end</code> tokens.</p>

CC BY-SA 4.0
2023-05-16T19:13:43.970Z
2023-05-16T19:13:43.970Z
Norman Ramsey
CC BY-SA 4.0
2023-07-04T13:32:35.043Z
That is the reason I added `ElseIf` to AEC (my programming language).
FlatAssembler
<p><code>else if</code> could never be an invalid construct in any reasonable language.</p>
<p>Languages that also use <code>elseif</code> tend to have enforced grouping constructs. That is, you cannot omit the braces or equivalents after the <code>if</code> conditions. In many cases it's because the language is using specific grouping constructs for every control structure, that is, <code>if</code>...<code>endif</code>, <code>for</code>...<code>endfor</code>. In other cases it's because grouping is an important part of the grammar, for example in Python and Tcl.</p>
<p>In these cases, if you don't use <code>elseif</code>, a long conditional statement would become:</p>
<pre><code>if(...)
    ...;
else
    if(...)
        ...;
    else
        if(...)
            ...;
        else
            ...;
        endif;
    endif;
endif;
</code></pre>
<p>which stacks many <code>endif</code>s at the end and is not very practical.</p>
<p>There are languages like PHP, where grouping constructs are not enforced, but also have <code>elseif</code>. Many people choose to use <code>else if</code> anyway, and some may not even realize <code>elseif</code> existed. So your design decisions may not matter that much, after all.</p>
<p>There are also languages like the LISP variants. Everybody already knows that code in them would always have this problem everywhere, so nobody cares about the little more problems caused by not having <code>elseif</code> with enforced grouping constructs.</p>

CC BY-SA 4.0
2023-07-03T10:40:14.210Z
2023-07-05T11:19:17.733Z
2023-07-05T11:19:17.733Z
user23013
<p><code>elseif</code>/<code>elsif</code>/<code>elif</code> is shorter, which is important in <a href="https://codegolf.stackexchange.com">Code Golf</a>.</p>

CC BY-SA 4.0
2023-07-04T08:13:30.230Z
2023-07-04T08:13:30.230Z
The Empty String Photographer
CC BY-SA 4.0
2024-02-19T18:53:06.837Z
There are much terser ways to write `if`-`else`-chains than by adding the `elif` keyword. Even in C you'd write something like `a?b:c?d:e?…`.
G. Sliepen
<p>They do this to avoid the <strong>dangling else problem</strong>.</p>
<p>In many programming languages, the syntax for else-if statements is ambiguous. For example, consider the following C program:</p>
<pre><code>if(a) if (b) x++; else y++;
</code></pre>
<p>Which <code>if</code> should the else belong to? Is it the inner one?</p>
<pre><code>if (a)
    if (b)
        x++;
    else
        y++;
</code></pre>
<p>or the outer one?</p>
<pre><code>if (a)
    if (b)
        x++;
else
    y++;
</code></pre>
<p>This ambiguity is known as the &quot;dangling else problem&quot;. One way that programming languages can avoid it is to require delimiters around the &quot;then&quot; and the &quot;else&quot; part of the <code>if</code>. Some languages, such as Swift, mandate that there must be curly braces:</p>
<pre><code>if (a) {
   x++;
} else {
   y++;
}
</code></pre>
<p>Some languages instead use <code>then</code> and <code>end</code> keywords, for a similar effect. For example, Lua:</p>
<pre><code>if a then
   x = x + 1
else
   y = y + 1
end
</code></pre>
<p>However, if our language requires these delimiters around the <code>else</code> then we cannot write <code>else if</code> as we do in C. Because <code>else</code> must be followed by an open curly brace, we would end up with open braces between the <code>else</code> and the <code>if</code>, and a long sequence of closing delimiters at the end.</p>
<pre><code>if (a) {
    x++;
} else { if (b) {
    y++;
} else { if (c) {
    z++;
} else {
    w++;
}}} /*ouch!*/
</code></pre>
<p>Having an <code>elseif</code> keyword is an elegant way to avoid this <code>}}}</code> avalanche. We can still mandate braces after <code>if</code> and <code>else</code>, but there aren't those pesky braces between the two</p>
<p>Swift and Rust avoid the <code>else { if</code> problem by special casing the <code>else if</code>. Their grammar says that the next token after the <code>else</code> must be a <code>{</code>, unless it's an <code>if</code>. This is certainly a valid way to solve the problem and avoids creating a new keyword. That said, the programmer must be aware that <code>else if</code> 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 <code>if</code> statement in the <code>else if</code>. In languages with <code>elseif</code> this question doesn't come up because it's loud and clear that <code>elseif</code> is special.</p>

CC BY-SA 4.0
2023-05-16T22:41:10.620Z
2023-07-07T01:49:20.407Z
2023-07-07T01:49:20.407Z
hugomg
CC BY-SA 4.0
2023-05-19T03:23:25.030Z
PHP is a clike just like C and JS, and it has `elseif`. I wonder what the reason is there, maybe to save the keystroke.
naffetS
CC BY-SA 4.0
2023-05-19T09:58:38.403Z
The dangling `else` problem doesn't contain any occurrences of `else if`, and would still occur in C's grammar if `elseif` were to be written instead. The point about block delimiters is reasonable, but I think it would be clearer if this answer said that it's a consequence of requiring delimiters around `if` and `else` blocks, which is done in part to avoid the dangling `else` problem but also for other reasons (hence such languages also tend to require block delimiters for loops, try/catch, and so on).
kaya3
CC BY-SA 4.0
2023-05-19T10:00:50.440Z
Also technically the dangling `else` problem could also be solved by only requiring braces around the `if` body, and not necessarily also the `else` body, which would allow `else if` to still be written. Though this might seem inconsistent to users of the language.
kaya3
CC BY-SA 4.0
2023-07-02T12:35:07.117Z
This may explain some languages, but Python uses `elif` and it does not suffer from the dangling else problem.
Jack Aidley
CC BY-SA 4.0
2023-07-02T14:25:38.183Z
In Python, the dangling else problem is avoided by significant indentation, which is analogous to mandating braces around the if/else body. Python's elif allows if-else-if without having to nest the elses in increasingly deeper levels of indentation (which would be analogous to the `}}}` problem discussed in my answer).
hugomg
CC BY-SA 4.0
2024-02-09T22:34:21.243Z
Perhaps I don't understand, but why is the dangling else problem a problem? Doesn't C unambiguously specify that it's the first of the options you gave since an else corresponds to its nearest if?
EE18
CC BY-SA 4.0
2024-02-09T23:56:03.737Z
The C specification does specify the nearest-if rule, so that all compilers will do the same thing with unbraced if-else. However, the real problem is that it's more confusing for programmers. The programmer might be thinking of the second option, but the compiler will actually do the first one.
hugomg
CC BY-SA 4.0
2024-02-20T21:22:49.953Z
More specifically, the programmer is likely to *write* the second version, and their use of indentation may think it will work as they expect, but it will actually be parsed as the first version. This is similar to what happens when they write a braceless `if` or `else` and later add a second statement without adding braces.
Barmar
# Why do some PL choose to have a dedicated keyword for elseif instead of like in C?
Posted by: username_0 on 2023-05-16
In C, `else if` is nothing but a new `if` statement after a single-statement `else` clause. Why do languages like Python and Ruby have a dedicated construct for `elsif`/`elif`?
**Tags:** syntax language-comparison
---
## 6 answers
### Answer by username_9 on 2023-05-16. Score: 36 | Accepted answer
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
Swift 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.
> **Comments:**
> **username_10** (2023-05-19): PHP is a clike just like C and JS, and it has `elseif`. I wonder what the reason is there, maybe to save the keystroke.  
> **username_11** (2023-05-19): The dangling `else` problem doesn't contain any occurrences of `else if`, and would still occur in C's grammar if `elseif` were to be written instead. The point about block delimiters is reasonable, but I think it would be clearer if this answer said that it's a consequence of requiring delimiters around `if` and `else` blocks, which is done in part to avoid the dangling `else` problem but also for other reasons (hence such languages also tend to require block delimiters for loops, try/catch, and so on).  
> **username_11** (2023-05-19): Also technically the dangling `else` problem could also be solved by only requiring braces around the `if` body, and not necessarily also the `else` body, which would allow `else if` to still be written. Though this might seem inconsistent to users of the language.  
> **username_12** (2023-07-02): This may explain some languages, but Python uses `elif` and it does not suffer from the dangling else problem.  
> **username_9** (2023-07-02): In Python, the dangling else problem is avoided by significant indentation, which is analogous to mandating braces around the if/else body. Python's elif allows if-else-if without having to nest the elses in increasingly deeper levels of indentation (which would be analogous to the `}}}` problem discussed in my answer).  
> **username_13** (2024-02-09): Perhaps I don't understand, but why is the dangling else problem a problem? Doesn't C unambiguously specify that it's the first of the options you gave since an else corresponds to its nearest if?  
> **username_9** (2024-02-09): The C specification does specify the nearest-if rule, so that all compilers will do the same thing with unbraced if-else. However, the real problem is that it's more confusing for programmers. The programmer might be thinking of the second option, but the compiler will actually do the first one.  
> **username_14** (2024-02-20): More specifically, the programmer is likely to *write* the second version, and their use of indentation may think it will work as they expect, but it will actually be parsed as the first version. This is similar to what happens when they write a braceless `if` or `else` and later add a second statement without adding braces.  
---
### Answer by username_3 on 2023-05-16. Score: 23
The way the chaining of else if blocks is defined in C follows naturally from the way the grammar allows for braceless blocks:
if (x) {
} else if (y) {
}

being parsed the same as
if (x) {
} else
    if (y) {
    }

i.e.
if (x) {
} else {
    if (y) {
    }
}

When you allow for such constructs in the syntax, a dedicated keyword is useless.
On the other hand, if you take Python, for example, since blocks are defined by indentation (and not by enclosing tokens such as braces), this is not valid out-of-the-box (you have to special-case it, whereas in C it was "free"):
if x:
    pass
else if y:
    pass

So, given that we're forced to create that special case, it makes sense to choose something shorter than else if, hence elif (or elsif).
---
### Answer by username_4 on 2023-05-16. Score: 16
Another reason for `elseif/elsif/elif` is if the conditional construct has a keyword terminator, like the shell's `fi` or Lua's `end`. You don't want to be writing `else if` because now you're writing nested `if`'s, which have to be terminated with a whole sequence of repeated `end` tokens.
> **Comments:**
> **username_5** (2023-07-04): That is the reason I added `ElseIf` to AEC (my programming language).  
---
### Answer by username_1 on 2023-05-16. Score: 13
They need one
In C-style languages like JS, you can put a single statement after an if to run just that one:
if (x == 1) print("x is 1!");

In fact, else if isn't even necessarily interpreted specially by the compiler. It could just be parsed as an if statement directly following the else.
However, in languages like Python where you can't do this, it would be natural to have a keyword specifically for else-if since you don't get that for free.
> **Comments:**
> **username_2** (2023-05-16): There are languages that have "else if" as separate words but do not allow a single expression after `if` (like Rust)  
> **username_1** (2023-05-16): @mousetail That's true, I was going to touch on how it's possible to detect an `else if` even without that, might come back and do that in a sec  
---
### Answer by username_6 on 2023-07-03. Score: 4
else if could never be an invalid construct in any reasonable language.
Languages that also use elseif tend to have enforced grouping constructs. That is, you cannot omit the braces or equivalents after the if conditions. In many cases it's because the language is using specific grouping constructs for every control structure, that is, if...endif, for...endfor. In other cases it's because grouping is an important part of the grammar, for example in Python and Tcl.
In these cases, if you don't use elseif, a long conditional statement would become:
if(...)
    ...;
else
    if(...)
        ...;
    else
        if(...)
            ...;
        else
            ...;
        endif;
    endif;
endif;

which stacks many endifs at the end and is not very practical.
There are languages like PHP, where grouping constructs are not enforced, but also have elseif. Many people choose to use else if anyway, and some may not even realize elseif existed. So your design decisions may not matter that much, after all.
There are also languages like the LISP variants. Everybody already knows that code in them would always have this problem everywhere, so nobody cares about the little more problems caused by not having elseif with enforced grouping constructs.
---
### Answer by username_7 on 2023-07-04. Score: 0
`elseif`/`elsif`/`elif` is shorter, which is important in [Code Golf](https://codegolf.stackexchange.com).
> **Comments:**
> **username_8** (2024-02-19): There are much terser ways to write `if`-`else`-chains than by adding the `elif` keyword. Even in C you'd write something like `a?b:c?d:e?…`.  
---
