Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a readable way to code a nested binary branching logic

I have a few logic that looks like

if(a){
 if(b){
  if(c){
    //do something
  }else{
    //do something
  }    
 }else{
  if(c){
    //do something
  }else{
    //do something
  }    
 }else{
 if(b){
  if(c){
    //do something
  }else{
    //do something
  }    
 }else{
  if(c){
    //do something
  }else{
    //do something
  }    
}

What is the best way tot implement this into readable logic? I dont want to do some big OOP surgery to make it readable because the do something is just one liner. Solution in C/C++ is appreciated

like image 757
leon Avatar asked Feb 18 '26 00:02

leon


2 Answers

Since the conditions are boolean, and apparently independent, treat them as bits in a word and switch on them:

#include <cstdio>

#define COMPOSE(a,b,c) ( ((!!(a)) << 2) | ((!!(b))<<1) | (!!(c)) )

int f(int i, int j, int k) {

  switch(COMPOSE( i==j, i+j<k, k!=42)) {
  case COMPOSE(true, true, true):
    printf("yo\n");
    break;
  case COMPOSE(true, true, false):
    printf("ye\n");
    break;
  case COMPOSE(true, false, true):
    printf("ya\n");
    break;
  }
}

int main () {
  f(1,1,1);
}
like image 62
Robᵩ Avatar answered Feb 19 '26 12:02

Robᵩ


If all //do something are fundamentally different, you don't have much choice (afaik).

For code style I would prefer

if ( a && b && c ) 
{
}
else if ( a && b && !c )
{
}
else if ( a && !b && c )
...

This removes the necessity of multiple levels of indentation and makes it clear which condition is actually satisfied.

Side note: obviously a && b && !c can be stated as a && b because !(a && b && c) and the use of else if. I would leave it there anyway because the compiler might optimize it and the code looks cleaner.

like image 29
stefan Avatar answered Feb 19 '26 14:02

stefan