我有这个(示例)代码:
int c = getchar();
int other_variable = rand();
// set conditions based on user input, etc.
if (c == 'a') {
// some code here
return;
}
if (c == 'b') {
// some code here
if (other_variable == 0)
return;
}
if (c == 'c') {
// some code here
return;
}
// rest of the conditions
我想通过使用else if
s并删除return
s来缩短此代码。我不知道怎么做,因为只有当other_variable
不是2时,程序才应该继续通过if语句。我该怎么办?
可能你可以在条件中添加检查并将身体留空:
if (condition1) {
do_something();
}
else if (condition2 && !do_stuff()) {
} else if (...)
但这令人困惑。如果您更多地考虑整个逻辑,您可能会找到更好的简化方法,而不仅仅是删除返回。