Ambiguous if and else branches: is the behavior defined?

I recently appeared in C ++ code, for example:

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

This is ambiguous, as the compiler could see it as:

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

or how:

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

Is the behavior of this code defined in accordance with any standard (C, C ++)? I saw this code in C ++, a VC ++ program that seems to have preferred the first solution.

+5
source share
4 answers

Is the behavior of this code defined in accordance with any standard (C, C ++)?

Yes, it is determined. In C (and all similar languages, as I know), the "dangling other" is associated with the last free, if, therefore, this interpretation

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

is correct.

+11
source

. else if, . ++ standard (6.4 ):

6 subsatement , . - ( else if) (3.3).

- , , , . [:

   if (x) int i;

     if (x) { 
           int i;
     }

, , , :

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

. else if.

+1
source

Defined in C. The parameter is elsealways connected to the nearest if; therefore, you must use the correct curly braces to avoid ambiguity.

0
source

All Articles