c++ - 如何避免 "if"链?

标签 c++ c if-statement control-flow

假设我有这个伪代码:

bool conditionA = executeStepA();
if (conditionA){
    bool conditionB = executeStepB();
    if (conditionB){
        bool conditionC = executeStepC();
        if (conditionC){
            ...
        }
    }
}

executeThisFunctionInAnyCase();

函数 executeStepX 当且仅当前一个成功时才应该执行。 在任何情况下,都应该在最后调用 executeThisFunctionInAnyCase 函数。 我是编程新手,很抱歉这个非常基本的问题:有没有办法(例如在 C/C++ 中)避免产生那种“代码金字塔”的长 if 链,以牺牲代码的易读性为代价?

我知道如果我们可以跳过 executeThisFunctionInAnyCase 函数调用,代码可以简化为:

bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;

但约束是 executeThisFunctionInAnyCase 函数调用。 break 语句可以以某种方式使用吗?

最佳答案

您可以使用 && (逻辑与):

if (executeStepA() && executeStepB() && executeStepC()){
    ...
}
executeThisFunctionInAnyCase();

这将满足您的两个要求:

  • executeStep<X>()仅当前一个成功时才应评估(这称为 short circuit evaluation)
  • executeThisFunctionInAnyCase()无论如何都会被执行

关于c++ - 如何避免 "if"链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430504/

相关文章:

c++ - D3D11 : Rendering (depth) to texture results in red square, 正常渲染工作

c++ - 变量在所有来源中必须是绝对全局的

c++ - 如何使用 decltype 实现不太通用的 std::is_constructible

c - 为什么更新的结构变量不打印

c++ - 如果使用某些过时的 C/C++ 函数,则防止使用 svn 提交代码

java - 如何在 C 中使用 Long 数据类型?

c++ - 我一直收到错误 "‘else’ 而没有之前的 ‘if’“并且不知道为什么

python - for 循环在 Python 中生成/导出输出的时间太长

c++ - 获取与字符串对应的类型,如 int、float 等

javascript - jQuery if else 语句和 data()