How do I avoid overlapping if statements?

Asked 2 years ago, Updated 2 years ago, 83 views

What if there's an if statement inside the if statement? It's hard to see /

psudo code)

bool conditionA = executeStepA(); //executeStepX only runs when the previous step is successful
if (conditionA){
    bool conditionB = executeStepB();
    if (conditionB){
        bool conditionC = executeStepC();
        if (conditionC){
            ...
        }
    }
}

executeThisFunctionInAnyCase(); //Code that runs unconditionally at the end

The way I thought of it is to write it like below, but executeThisFunctionInAnyCase() can't be executed. What can I do?

psudo code)

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

c c++ control-flow if문

2022-09-22 16:51

1 Answers

psudo code)

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

(expression1 && expression2 && expression3 && ...) is checked from left to right If expressionN is false, it is not evaluated afterwards and exits the if statement So you can keep the order in the if statement.

If you make the most of your code, you can write as follows.

psudo code)

void foo()
{
bool conditionA = executeStepA();
if (!conditionA) return;

  bool conditionB = executeStepB();
if (!conditionB) return;

  bool conditionC = executeStepC();
if (!conditionC) return;
}

void bar()
{
foo();
executeThisFunctionInAnyCase();
}


2022-09-22 16:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.