I’ve wondered about the implementation of else if before, specifically why two keywords are needed, and why the keywords aren’t joined. In python though, elif is used as the else if control flow statement. I was wondering how a general compiler would interpret else if.
Does a compiler treat else if as a single token? Or is else if simply an else with implicit block scope that transfers through to the if underneath?
Single Token:
if (some_condition) {
some_statement();
}
else_if (some_other_condition) {
other_statement();
}
else {
default_statement();
}
Or Else then If:
if (some_condition) {
some_statement();
}
else { // compiler generated block scope
if (some_other_condition) {
other_statement();
}
else {
default_statement();
}
}
I’m aware that different languages and compilers could implement this differently, but if anyone has specific details about a particular language (or compiler) I’d be interested to hear them.
In C, at least,
else ifis not a separate language construct. As you guessed, it’s no different fromif (x) { ... } else { if (y) { ... } }.In certain languages (and presumably Python is one of them), then syntax/whitespace rules wouldn’t allow the parser to interpret
else ifcorrectly, hence theelif(or equivalent) construct.