【问题标题】:Else-if in a complex function复杂函数中的 Else-if
【发布时间】:2017-05-17 03:25:27
【问题描述】:

我有这个(示例)代码:

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 语句。我该怎么办?

【问题讨论】:

  • 不是很清楚,这个应该不在codereview.stackexchange.com?
  • 我正在做出一些飞跃和假设。如果当前函数的 ret 类型是 void,你不应该把if (!do_stuff()) return; 放在顶部吗?如果这不是您想要的,请提供mvce
  • 如果您能详细说明需求,那就太好了。我们不能仅根据我们的假设为您提供帮助,
  • @VimalBhaskar 完成。
  • @Stargateur 我澄清了。

标签: c if-statement return


【解决方案1】:

也许你可以在条件中添加检查并将正文留空:

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

} else if (...)

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

【讨论】:

    猜你喜欢
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多