c ++标准中的if..else语句 [英] if..else statement in the c++ standard

查看:226
本文介绍了c ++标准中的if..else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

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.

第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

我认为 else if(){} 语句是 if(){} else {}
现在看来这个 else if {} 语句只是一个else语句,里面有它自己的 if(){} 所以这两个代码是相等的:

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) {

    }

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

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 {

    }

关于最后一个代码:当我们写一个没有卷曲的else语句时大括号只有第一个语句与 else 相关联,因为其他语句不属于 else (它们不是第一个语句的花括号)。因此编译器说第二个 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?

推荐答案

if (condition) statement else statement

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

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.

这篇关于c ++标准中的if..else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆