否则 - 如果是复杂的功能

问题描述 投票:-3回答:1

我有这个(示例)代码:

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

c if-statement return
1个回答
2
投票

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

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

} else if (...)

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

© www.soinside.com 2019 - 2024. All rights reserved.