如果没有大括号,如何识别里面的一个语句?
How can identify the one statement inside if without braces?
通常没有大括号我们定义一个语句所以
我想问
if ( n > 0 )
if ( m > 0 )
printf("Condition satisfied.");
这是一个声明还是
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
所以我问上面两个代码哪个是正确的代码?并给出此代码
if(a > b)
if(b > c)
s1;
else s2;
s2 will be executed if
在这种情况下:
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
else
与最里面的 if
配对。所以上面是一样的:
if ( n > 0 ) {
if ( m > 0 ) {
printf(" Condition satisfied.");
} else {
printf(" condition not satisfied. ");
}
}
这种情况可能会造成混淆,因此除非您可以将整个语句干净利落地放在一行中,否则请始终使用大括号来清楚说明内容。
本 C 教程解释了 C 语言中的“悬挂 else”。它解释了嵌套 if 语句中单个 else 语句的关联。
在嵌套的 if 语句中,当出现单个“else 子句”时,情况恰好是悬空 else!例如:
if (condition)
if (condition)
if (condition)
else
printf("dangling else!\n"); /* dangling else, as to which if statement, else clause associates */
1.在这种情况下,else 子句属于最接近的不完整的 if 语句,即最里面的 if 语句!
2. 但是,我们可以通过将所有 if 语句包含在 if 语句之外的块中来使 else 子句属于所需的 if 语句,以将 else 子句关联起来。例如:
if (condition) {
if (condition)
if (condition)
} else
printf("else associates with the outermost if statement!\n");
当你写类似
的东西时
if(n > 0)
if(m > 0)
printf("Condition satisfied.\n");
else
printf("Condition not satisfied.\n");
那么,是的,您遇到了“悬而未决”的问题。很难弄清楚 if
和 else
对应的是哪个。通过使用显式大括号,您可以明确地将 else
与正确的 if
.
相关联
但是,在这种情况下,将 else
与 if
中的任何一个相关联都是不正确的!在这种情况下,我相信你会想这样写:
if(n > 0 && m > 0)
printf("Condition satisfied.\n");
else printf("Condition not satisfied.\n");
现在,它不仅更小、更易于阅读,不仅没有悬垂的 else 问题,而且您将始终获得正确的结果,并打印一条或另一条消息。
通常没有大括号我们定义一个语句所以
我想问
if ( n > 0 )
if ( m > 0 )
printf("Condition satisfied.");
这是一个声明还是
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
所以我问上面两个代码哪个是正确的代码?并给出此代码
if(a > b)
if(b > c)
s1;
else s2;
s2 will be executed if
在这种情况下:
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
else
与最里面的 if
配对。所以上面是一样的:
if ( n > 0 ) {
if ( m > 0 ) {
printf(" Condition satisfied.");
} else {
printf(" condition not satisfied. ");
}
}
这种情况可能会造成混淆,因此除非您可以将整个语句干净利落地放在一行中,否则请始终使用大括号来清楚说明内容。
本 C 教程解释了 C 语言中的“悬挂 else”。它解释了嵌套 if 语句中单个 else 语句的关联。 在嵌套的 if 语句中,当出现单个“else 子句”时,情况恰好是悬空 else!例如:
if (condition)
if (condition)
if (condition)
else
printf("dangling else!\n"); /* dangling else, as to which if statement, else clause associates */
1.在这种情况下,else 子句属于最接近的不完整的 if 语句,即最里面的 if 语句! 2. 但是,我们可以通过将所有 if 语句包含在 if 语句之外的块中来使 else 子句属于所需的 if 语句,以将 else 子句关联起来。例如:
if (condition) {
if (condition)
if (condition)
} else
printf("else associates with the outermost if statement!\n");
当你写类似
的东西时if(n > 0)
if(m > 0)
printf("Condition satisfied.\n");
else
printf("Condition not satisfied.\n");
那么,是的,您遇到了“悬而未决”的问题。很难弄清楚 if
和 else
对应的是哪个。通过使用显式大括号,您可以明确地将 else
与正确的 if
.
但是,在这种情况下,将 else
与 if
中的任何一个相关联都是不正确的!在这种情况下,我相信你会想这样写:
if(n > 0 && m > 0)
printf("Condition satisfied.\n");
else printf("Condition not satisfied.\n");
现在,它不仅更小、更易于阅读,不仅没有悬垂的 else 问题,而且您将始终获得正确的结果,并打印一条或另一条消息。