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 开发者_StackOverflow中文版 // 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).
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();
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;
}
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
.
Don't ever write code like this in a production environment. It will bite you.
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.
This is called "Dangling else" problem. The convention to solve this is to attach the 'else' to the nearest 'if' statement.
Dangling else wikipedia
精彩评论