Ambiguous if and else branches: Is the behaviour defined?

前端 未结 5 1956
既然无缘
既然无缘 2021-01-18 11:33

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

if(test_1)
    if(test_2)
    {
         // Do stuff
    }
    else
       exit(0);
5条回答
  •  天命终不由人
    2021-01-18 12:19

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

提交回复
热议问题