Home > front end >  How to simplify if statements
How to simplify if statements

Time:09-29

How can I simplify below if statements?, I'm trying to achieve the possibly most efficient code.

// doSomething based on x value and y value   
void doSomething(x int, y int) {

    //x not zero and y not zero
    if (x != 0 && y != 0) {
      //do a

      //do b if x greater or equal y
      //else do c
      if (x >= y) {
          //do b
      } else (x < y) {
          //do c
      }

      return;
        
    }

    //do b if x not zero and y zero
    if (x != 0 && y == 0) {
        //do b
        return;
    }

    //do e if both x and y zero
    if (x == 0 && y == 0) {
        //do e
        return;
    }
}

What is the most concise and efficient way to simplify?

CodePudding user response:

As it stands, your code is equivalent to:

if (x == 0)
{
  if (y == 0)
    do e
}
else if (y != 0)
{
  if (x < y)
    do a,c
  else
    do a,b
}

In particular:

  • if x=0 && y!=0 or y=0 && x!=0, then do nothing;
  • the two branches //do b if x not zero and y zero and //do d if x zero and y not zero are unreachable in your code.

CodePudding user response:

assuming a(), b(), and e() have the same type (fxtype)

fxtype *fx[4] = { e, NULL, b, a }; // NULL when x==0, y!=0
fx[2*!!x   !!y](x, y);

Change a to include c() and b()

int a(int x, int y) {
    // do previous a()
    if (x < y) c(x, y); else b(x, y);
    return 0;
}
  • Related