问题描述
从C ++标准第6.4.1节: if语句:
From the C++ standard section 6.4.1: The if statement:
第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 {} 的单独声明STRONG>。
现在看来这个 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语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!