开发者

Ambiguous if and else branches: Is the behaviour defined?

I recently came accross some C++ code like the following:

if(test_1)
    if(test_2)
    {
         // Do stuff
    }
    else
       exit(0);

This is ambiguous, since the compiler could see this as:

if(test_1)
{
    if(test_2)
    {
    }
    else
    {
    }
}

or as:

if(test_1)
{
    if(test_2)
    {
    }
}
else
{
}

Is the behaviour of this code defined according to any standard (C, C++)? I saw this code in a C++ program on VC++, which seems to prefered the first solutio开发者_Python百科n.


Is the behaviour of this code defined according to any standard (C, C++)?

Yes, it is defined. In C (and all similar languages as I know), the "dangling else" binds to the last free if, therefore this interpretation

if(test_1)
{
    if(test_2)
    {
    }
    else
    {
    }
}

is correct.


There is no ambiguity. The else clause always refers to the closest if it can be attached to. From the C++ standard (6.4 Selection statements):

In clause 6, the term substatement refers to the contained statement or statements that appear in the syntax notation. The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a local scope (3.3).

If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement. [ Example:

   if (x) int i;

can be equivalently rewritten as

     if (x) { 
           int i;
     }

It ensues that the code you wrote can be rewritten as:

if(test_1)
{
    if(test_2)
    {
        // Do stuff
    }
    else
    {
        exit(0);
    }
}


It is well defined. else is always paired with the nearest available if.


It is Defined in C. An else always gets paired with nearest if; therefore you should use proper braces to avoid ambiguity.


Yes its not ambiguous, as the rules state where it is applied, but my GCC C++ compiler still gives a warning stating it is :

/brainModule/BrainModule.cpp: In function ‘void failExpiredPendingAndRunning()’: ../brainModule/BrainModule.cpp:158:16: warning: suggest explicit braces to avoid ambiguous ‘else’ [-Wparentheses] if (job->isExpired() == false)

g++ (Raspbian 6.3.0-18+rpi1+deb9u1) 6.3.0 20170516

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜