Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if..else statement in the c++ standard

From the C++ standard section 6.4.1: The if statement:

If the condition (6.4) yields true the first substatement is executed. If the else part of the selection statement is present and the condition yields false, the second substatement is executed. In the second form of if statement (the one including else), if the first substatement is also an if statement then that inner if statement shall contain an else part.

Section 6.4: Selection statements:

Selection statements choose one of several flows of control.
    selection-statement:
        if ( condition ) statement
        if ( condition ) statement else statement
    condition:
       expression
       attribute-specifier-seqopt decl-specifier-seq declarator = initializer-clause
       attribute-specifier-seqopt decl-specifier-seq declarator braced-init-list

I thought that else if() {} statement was a separate statement from if() {} and else {}. Now it seems that this else if {} statement is just an else statement with it's own if() {} inside it so these two codes are equal:

if(condition) {

    }
    else {
        if(condition) {

        }
    }

if(condition) {

    }
    else if(condition) {

    }

Now what if we have multiple else if-s? These codes are also equal in C++:

if(condition) {

    }
    else {
        if(condition) {

        }
        else {
            if(condition){

            }
        }
    }

if(condition) {

    }
    else if {

    }
    else if {

    }

About the last code: When we write an else statement without curly braces only the first statement is associated to the else because the other statements are not part of that else(they are not in curly braces with the first statement). So isn't it logical for the compiler to say that the second else is not associated with an if statement?

like image 221
LearningMath Avatar asked Dec 06 '22 01:12

LearningMath


2 Answers

if (condition) statement else statement

is a single selection-statement. This means that the entire if...else is the substatement of a previous else.

or in other words, you start rolling up the statements from the bottom.

like image 142
Sebastian Redl Avatar answered Dec 30 '22 15:12

Sebastian Redl


The else is part of the if statement it corresponds to. In the case of:

if(condition) {

}
else if {

}
else if {

}

The nested statements are as follows:

if (condition) { } else // first statement
  if { } else           // second statement
    if { }              // third statement

So the second else is associated with the second if.

like image 31
Joseph Mansfield Avatar answered Dec 30 '22 15:12

Joseph Mansfield