views:

93

answers:

5

With the following c++ example(indention was left out in purpose).

if(condA)          // if #1
if(condB)          // if #2
if(condC)          // if #3
if(condD)          // if #4
funcA();
else if(condD)     // else #1 if #5
funcB();
else if(condE)     // else #2 if #6
funcC();
else               // else #3
funcD();
else if(condF)     // else #4 if #7
funcE();
else               // else #5
funcF();

What else refers to what if and what is the rule about this? (yes I know using { } will solve this).

+5  A: 
if(condA)          // if #1
    if(condB)          // if #2
        if(condC)          // if #3
            if(condD)          // if #4
                funcA();
            else if(condD)     // else #1 if #5
                funcB();
            else if(condE)     // else #2 if #6
                funcC();
            else               // else #3
                funcD();
        else if(condF)     // else #4 if #7
            funcE();
        else               // else #5
            funcF();
DeadMG
+3  A: 

Each else always refers to the inner-most if possible.

So

if (a)
if (b) B;
else C;

is equivalent to

if (a) {
  if (b) B;
  else C;
}
sth
+1  A: 

Don't ever write code like this in a production environment. It will bite you.

C Johnson
It seems like more of a theoretical problem, and a very practical one when analyzing languages.
Stargazer712
It did bit me, but I didn't write the code, and I needed to know wtf does it do.
Dani
@Stargazer: Yes you are right, but only for those who write programming languages. Which is very few of us. @Dani: Ouch, I'm sorry you had to maintain that code. My condolences. :)
C Johnson
@ C Johnson: I had never seen code like that written outside of a theoretical environment, so I assumed it must be a theoretical question :). My condolences as well.
Stargazer712
+1  A: 

DeadMG is right. Just in case you are interested, the rule is

else is attached to the last free (that is, unprotected by braces and without corresponding else) if.

jpalecek
A: 

The convention is to attach the 'else' to the nearest 'if' statement. This is called "Dangling else" problem.

Dangling else wikipedia

Jaime