How to avoid quot;ifquot; chains?(如何避免“如果链?)
问题描述
假设我有这个伪代码:
bool conditionA = executeStepA();
if (conditionA){
bool conditionB = executeStepB();
if (conditionB){
bool conditionC = executeStepC();
if (conditionC){
...
}
}
}
executeThisFunctionInAnyCase();
函数 executeStepX
当且仅当前一个成功时才应执行.在任何情况下,都应该在最后调用 executeThisFunctionInAnyCase
函数.我是编程新手,很抱歉这个非常基本的问题:有没有办法(例如在 C/C++ 中)避免产生那种代码金字塔"的长 if
链, 以牺牲代码易读性为代价?
Functions executeStepX
should be executed if and only if the previous succeed.
In any case, the executeThisFunctionInAnyCase
function should be called at the end.
I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if
chain producing that sort of "pyramid of code", at the expense of the code legibility?
我知道如果我们可以跳过 executeThisFunctionInAnyCase
函数调用,代码可以简化为:
I know that if we could skip the executeThisFunctionInAnyCase
function call, the code could be simplified as:
bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;
但约束是 executeThisFunctionInAnyCase
函数调用.break
语句可以以某种方式使用吗?
But the constraint is the executeThisFunctionInAnyCase
function call.
Could the break
statement be used in some way?
推荐答案
您可以使用 &&
(逻辑与):
You can use an &&
(logic AND):
if (executeStepA() && executeStepB() && executeStepC()){
...
}
executeThisFunctionInAnyCase();
这将满足您的两个要求:
this will satisfy both of your requirements:
executeStep
仅在前一个成功时才应评估(这称为 短路评估)() executeThisFunctionInAnyCase()
任何情况下都会执行
executeStep<X>()
should evaluate only if the previous one succeeded (this is called short circuit evaluation)executeThisFunctionInAnyCase()
will be executed in any case
这篇关于如何避免“如果"链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何避免“如果"链?
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01