c ++标准中的if..else语句

Lea*_*ath 4 c++ if-statement

从C++标准第6.4.1节:if语句:

如果条件(6.4)产生真,则执行第一个子语句.如果选择语句的else部分存在且条件产生false,则执行第二个子语句.在if语句的第二种形式(包括else的那个)中,如果第一个子语句也是if语句,则该内部if语句应包含else部分.

第6.4节:选择陈述:

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
Run Code Online (Sandbox Code Playgroud)

我认为if if(){}语句是if(){}else {}的单独语句.现在似乎这个其他如果{}语句只是一个else语句,它内部有if(){},所以这两个代码是相等的:

if(condition) {

    }
    else {
        if(condition) {

        }
    }

if(condition) {

    }
    else if(condition) {

    }
Run Code Online (Sandbox Code Playgroud)

现在如果我们有多个if-s怎么办?这些代码在C++中也是相同的:

if(condition) {

    }
    else {
        if(condition) {

        }
        else {
            if(condition){

            }
        }
    }

if(condition) {

    }
    else if {

    }
    else if {

    }
Run Code Online (Sandbox Code Playgroud)

关于最后一个代码:当我们写一个else语句没有大括号只有第一条语句被关联到其他,因为其他语句不的那部分否则(它们不是在大括号中的第一份陈述).因此编译器说第二个else与if语句没有关联是不合逻辑的?

Seb*_*edl 7

if (condition) statement else statement
Run Code Online (Sandbox Code Playgroud)

是一个单一的选择陈述.这意味着整个if...else是前一个的子语句else.

换句话说,你开始从底部汇总语句.