views:

146

answers:

2

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?

+6  A: 

In C++, the two are exactly identical. Check out the formal grammar. In the example you gave, the if in else if is 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 with else if, though.

Roughly, the grammar defines:

<if structure> -> if <condition> <code blob> else <code blob>
<code blob> -> <if structure>

So when you do

 if (1) do(); else if (3) stuff(); else thing();` 

the whole piece

 if (3) stuff(); else thing();

is just the <code blob> of the else in the first if/else structure.

JoshD
+2  A: 

I'm sure any decent compiler will generate the same code for both forms. The only reason I can think of for using the second form is that you expect to add code to the else that is not controlled by the enclosed if.

Ferruccio