Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One 'else' for nested 'if' statements

I've got a problem which can be simplified to this:

parameters: a, b

if (a > 5)
{
    Print("Very well, a > 5");

    if (b > 7)
        Print("Even better, b > 7");
    else
    {
        Print("I don't like your variables");
    }
}
else
{
    Print("I don't like your variables");
}

I would like to use only one else instead of two since they are the same code. What I thought of was creating an additional method, which will return combined true`false`, but this is a serious overkill.

Another option would be a goto, but this would make code less readable and unsafe.

What is the way to do it, avoiding checking the same condition many times and making it as readable as possible?

like image 494
Michał Avatar asked Mar 24 '14 22:03

Michał


People also ask

Can we use else if in nested IF?

nested-if in C/C++ A nested if in C is an if statement that is the target of another if statement. Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.


1 Answers

void doILikeYourVariables(int a, int b) {
  if (a > 5) {
    Print("Very well, a > 5");
    if (b > 7) {
      Print("Even better, b > 7");
      return;
    }
  }
  Print("I don't like your variables");
}
like image 176
Chris Drew Avatar answered Sep 28 '22 16:09

Chris Drew