C++

Asked • 10/04/19

How to avoid "if" chains?

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. 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? 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; But the constraint is the `executeThisFunctionInAnyCase` function call. Could the `break` statement be used in some way?

1 Expert Answer

By:

Patrick B. answered • 10/05/19

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.