I know this is going to not be the same across all languages, but it’s something I’ve wondered for awhile.
Since the title isn’t very clear, is there a technical difference between
if (...) {
// ...
} else if (...) {
// ...
}
and
if (...) {
...
} else {
if (...) {
...
}
}
I know from a practical perspective, they will do the same thing, and there are readability reasons for choosing one over the other, such as if the second if doesn’t relate directly to the first.
But from a technical perspective, I’m not sure. Do compilers tend to do something special with an else if, or is it handled as though it were a single line thing, like:
if (...)
singleLine();
but looking like:
else
if (...) // Counts as just a single line command
Hope that makes it clear what I’m asking. Is there a technical difference between the two ways of doing it, and is there any disadvantage to using the else { if style?
In C++, the two are exactly identical. Check out the formal grammar. In the example you gave, the
ifinelse ifis really a new chunk of code, just as you’ve shown in your question it’s analogous to a single line. The formatting and code layout is nicer withelse if, though.Roughly, the grammar defines:
So when you do
the whole piece
is just the
<code blob>of the else in the first if/else structure.