【发布时间】:2011-08-05 14:28:37
【问题描述】:
在 if 块内或 else 块内嵌套 if 语句哪个更好?
一个。
if (cond1)
if (cond2){
statement1;
statement2;
...
}
else {
statement3;
statement4;
...
}
else {
statement5;
statement6;
...
}
b.
if (!cond1) {
statement5;
statement6;
...
}
else if (cond2) {
statement1;
statement2;
...
}
else {
statement3;
statement4;
...
}
感谢到目前为止的回复。我刚刚编辑了选项,但我主要关心的是:如果您有选择,(通过更改条件表达式)将 if 语句嵌套在更高级别的 if 语句块或 else 块中是否更好? (a) 只是将 if 嵌套在 if 块中的示例,(b) 是将 if 嵌套在 else 块中的示例。再次感谢大家的时间。
【问题讨论】:
-
您应该根据贾斯汀的评论编辑您的示例。您是在寻找
if (cond) ... else if (cond2) {...} else {...}还是if (cond) ... else { if (cond2) {...} else {...}}?或者正如贾斯汀所说,嵌套的 if 与逻辑与?谢谢。 -
这读起来非常模棱两可(我什至不知道正确的解析),所以请在第一种情况下在块周围添加花括号!
标签: coding-style if-statement nested