Daniel
Daniel

Reputation: 31609

Control flow syntax in c++

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).

Upvotes: 2

Views: 378

Answers (6)

Jaime
Jaime

Reputation: 6814

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

Dangling else wikipedia

Upvotes: 0

Ira Baxter
Ira Baxter

Reputation: 95420

C++ knows which else matches which if, and C++ compilers have just-fine parsers that sort this out in flash. The problem is the you aren't good at this.

Run this through a C++ prettyprinter and the result formatted text will make it very clear.

Upvotes: 0

jpalecek
jpalecek

Reputation: 47770

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.

Upvotes: 1

C.J.
C.J.

Reputation: 16111

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

Upvotes: 1

sth
sth

Reputation: 229844

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;
}

Upvotes: 3

Puppy
Puppy

Reputation: 147028

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();

Upvotes: 5

Related Questions