【发布时间】:2014-08-25 18:57:02
【问题描述】:
来自 C++ 标准第 6.4.1 节:if 语句:
如果条件 (6.4) 的结果为真,则执行第一个子语句。如果选择的 else 部分 语句存在且条件为假,第二个 子语句被执行。在 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
我认为 else if() {} 语句是独立于 if() {} 和 else {} 的语句。 现在看来,这个 else if {} 语句只是一个 else 语句,里面有它自己的 if() {} 所以这两个代码是相等的:
if(condition) {
}
else {
if(condition) {
}
}
if(condition) {
}
else if(condition) {
}
现在如果我们有多个 else if-s 怎么办?这些代码在 C++ 中也是一样的:
if(condition) {
}
else {
if(condition) {
}
else {
if(condition){
}
}
}
if(condition) {
}
else if {
}
else if {
}
关于最后一个代码:当我们编写不带花括号的 else 语句时,只有第一个语句与 else 相关联,因为其他语句不属于该 else (它们不在第一条语句的花括号中)。那么编译器说第二个 else 不与 if 语句关联是不是合乎逻辑的?
【问题讨论】:
-
技术上没有单独的
else语句,它是if语句的可选部分。 -
我知道这一点,我在上面的帖子中写道。我的问题在我的帖子末尾。
-
您自己引用了相应的语法:
if ( condition ) statement else statement所以我不确定您在问什么,每个 else 都是 if 的 else,那么您认为还有哪些 else 没有 if?跨度> -
说第二个 else 不与 if 语句关联是不“合乎逻辑的”,因为它是关联的。尝试在没有 if 的情况下使用 else。
-
还会是什么?
标签: c++ if-statement