Dangling else problem

What is a dangling else problem? It's presented below - what will print this program?

#include <iostream>

int main()
{
    bool a = true;
    bool b = false;
    
    if(a)
        if (b)
            std::cout << "foo" << std::endl;
    else
        std::cout << "bar" << std::endl;

   return 0;
}

It may seem that it won't print anything, but isn't true - on the screen we will see "bar". That's because the "else" is bound to the last "if" statement that wasn't already bound to other "else".

This may lead to bugs and confusion. One easy way is to always embrace body of the "if" statement in brackets. If we want to bind the "else" to the first "if" then correct parenthesis should be added as below:

    if(a)
    {
        if (b)
        {
            std::cout << "foo" << std::endl;
        }
    }
    else
    {
        std::cout << "bar" << std::endl;
    }

If we want to bound it to the second "if", it should be:

    if(a)
    {
        if (b)
        {
            std::cout << "foo" << std::endl;
        }
        else
        {
            std::cout << "bar" << std::endl;
        }
    }

What is good is that compilers will usually produce a warning in places where this error may exist:

 In function 'int main()':
8:7: warning: suggest explicit braces to avoid ambiguous 'else' [-Wparentheses]

0 commentaires:

Post a Comment