否则 - 如果是复杂的功能

时间:2017-01-03 05:01:13

标签: c if-statement return

我有这个(示例)代码:

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并删除return来缩短此代码。我不知道该怎么做,因为程序应该只在other_variable不是{2}时才继续通过if语句2.我该怎么办?

1 个答案:

答案 0 :(得分:2)

您可以在条件中添加检查并将身体留空:

if (condition1) {
    do_something();
}    
else if (condition2 && !do_stuff()) {

} else if (...)

但这令人困惑。如果你更多地考虑整个逻辑,你可能会发现更好的简化方法而不仅仅是删除回报。

相关问题