問題:
Assuming I have this pseudo-code: 假設我有這個僞代碼:
bool conditionA = executeStepA();
if (conditionA){
bool conditionB = executeStepB();
if (conditionB){
bool conditionC = executeStepC();
if (conditionC){
...
}
}
}
executeThisFunctionInAnyCase();
Functions executeStepX
should be executed if and only if the previous succeed. 僅當前一個成功時才應執行函數executeStepX
。 In any case, the executeThisFunctionInAnyCase
function should be called at the end. 無論如何,應該在最後調用executeThisFunctionInAnyCase
函數。 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? 我在編程的新手,對於非常基本的問題,很抱歉:有沒有辦法(在C / C ++爲例),以避免長if
鏈生產之類的“代碼金字塔”,在代碼的代價易讀?
I know that if we could skip the executeThisFunctionInAnyCase
function call, the code could be simplified as: 我知道,如果我們可以跳過executeThisFunctionInAnyCase
函數調用,則代碼可以簡化爲:
bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;
But the constraint is the executeThisFunctionInAnyCase
function call. 但是約束是executeThisFunctionInAnyCase
函數調用。 Could the break
statement be used in some way? 可以以某種方式使用break
語句嗎?
解決方案:
參考一: https://en.stackoom.com/question/1eVUO參考二: https://stackoom.com/question/1eVUO