-6

I need to combine 3 bools to test for the entire truth table (8 combinations) in c++.

I have 2 special cases that need to be attended to, they are a, b and c are all true, and a, b are true but c is false.

The rest don't need to be catered for specifically (they will work automatically together without case-specific instructions)

is there a way to only test for these two cases, and then the individual cases but still allow the individuals to work together?

Such as,

if(a && b && c)

and if(a && b && !c)

then if a, if b, if c respectively

I think it uses if else, but I'm having no luck, the way I have it now performs some operations twice as "a" is true in a b c, a b !c and also in a.

I hope this is clear enough, my first time posting here so apologies if it is not.

1 Answers1

1

Your two special cases can be handled something like:

if (a && b)
    if (c)
        all_true();
    else
        ab_true_c_false();

Another possibility would be to combine the three arithmetically, then use the result as an index:

typedef void (*action)();

// handlers for the individual cases:
void all_false() { std::cout << "all_false"; }
void a_true() { std::cout << "a true"; }
// ...

// table of handlers. The order of handlers in the array is critical.
static const action actions[] = { 
   all_false, a_true, b_true, ab_true, 
   c_true, ac_true, bc_true, abc_true };

// Create index into array 
int x = a | (b << 1) | (c << 2);

// invoke correct handler:    
actions[x]();
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Thanks for the answer, how would I then test for the other 3 cases individually, without repeating the processes (a, b and c are all "if true do this") – quantumspade Nov 02 '16 at 00:01
  • @quantumspade: the table can contain pointers to the same function in multiple places if desired. – Jerry Coffin Nov 02 '16 at 00:06