c+中的if..else语句+;标准 >从C++标准部分6.4.1: if语句< /强>: 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
如果条件(6.4)为真,则执行第一个子语句。如果选择的else部分 语句存在,条件产生false,第二个 执行子语句。在if语句的第二种形式中 包括else),如果第一个子语句也是if语句 然后,内部if语句应包含else部分 第6.4节:选择声明:c+中的if..else语句+;标准 >从C++标准部分6.4.1: if语句< /强>: 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,c++,if-statement,C++,If Statement,如果条件(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
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(){},所以这两个代码是相等的:
if(condition) {
}
else {
if(condition) {
}
}
if(condition) {
}
else if(condition) {
}
现在如果我们有多个其他if-s呢?这些代码在C++中也是相同的:
if(condition) {
}
else {
if(condition) {
}
else {
if(condition){
}
}
}
if(condition) {
}
else if {
}
else if {
}
关于最后一段代码:当我们编写一条没有大括号的else语句时,只有第一条语句与else关联,因为其他语句不是else的一部分(它们与第一条语句不在大括号中)。那么,编译器说第二个else与if语句没有关联,这难道不合乎逻辑吗
if (condition) statement else statement
是单个选择语句。这意味着整个if…else
是前一个else
的子状态
或者换句话说,您开始从底部滚动语句。如果它对应于
语句,则else
是语句的一部分。在下列情况下:
if(condition) {
}
else if {
}
else if {
}
嵌套语句如下所示:
if (condition) { } else // first statement
if { } else // second statement
if { } // third statement
因此,第二个else与第二个if关联。不,编译器说第二个else与if语句不关联是不合逻辑的。这些规则的原因是为了解决一个称为问题的问题
它在这样的代码中抬起头
if (A)
if (B) DoB();
else DoC();
何时执行DoC()
?当A
为false
时是否会发生这种情况?或者当A
为true
且B
为false
时会发生这种情况吗
编译器没有合乎逻辑的方法来解决这种情况。因此,在正常的解析规则之外,6.3声明在这种模棱两可的情况下,else属于内部if语句。从技术上讲,没有单独的else
语句,它是if
语句的可选部分。我知道这一点,我在上面的帖子中写道。我的问题在我文章的末尾。你自己引用了相应的语法:if(condition)statement else语句
所以我不确定你在问什么,每个其他语句都是if的else,那么你认为哪个其他语句是wihtout any if?这不是“编译器的逻辑”说第二个else与if语句没有关联——因为它是关联的。尝试在没有if的情况下使用else。它还会是什么?“这意味着整个if…else是先前else的替代品。”-谢谢。这就是我一直在寻找的答案。我不知道你的观点是什么。第一个if没有else,else语句与第二个if关联。你能更具体一点吗?对不起,我解决了这个问题。所以,正如@Sebastian Redl所说,整个if-else是一个子状态。这里是第一个if语句的子语句。如果是像我以前想的那样,那么这个问题就发生了。非常好的回答,谢谢你指出这一点。澄清这种(错误的)歧义正是大多数编码规则建议在if语句中始终使用大括号的原因。当前的GCC会对该代码发出警告。