What is a readable coding method for embedded binary branch logic

I have some 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 to implement this in readable logic? I do not want to do any major OOP operation to make it readable, because doing something is just one liner. Solution in C / C ++ is evaluated

+3
source share
2 answers

Since the conditions are Boolean and apparently independent, consider them as bits in a word and switchon 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);
}
+5
source

If everything is //do somethingfundamentally different, you do not 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 eliminates the need for several levels of indentation and makes it clear which condition is actually fulfilled.

: , a && b && !c a && b, !(a && b && c) else if. , , .

+5

All Articles