Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for all bools YES or all bools NO?

Often in my code I need to check whether the state of x amount of bools are all true OR all bools are false. So I do:

BOOL first, second, third;
if((first && second && third) || (!first && !second && !third))
     //do something

Being a lazy programmer, I want to know if there is some mathematical shorthand for this kind of query, instead of having to type out this whole thing every time?

like image 415
Snowman Avatar asked Dec 21 '22 17:12

Snowman


2 Answers

The shorthand for all bools the same is testing for (pairwise) equality:

(first==second && second==third)

Of course you can expand this to any number of booleans, having N-1 equality checks joined with the and operator.

like image 77
Howard Avatar answered Jan 11 '23 10:01

Howard


If this is something you frequently require then you're better off using an integer and reading bits individually.

For instance, instead of:

BOOL x; // not this
BOOL y; // not this
BOOL z; // not this

...and instead of bit fields (because their layout is implementation-defined):

unsigned int x : 1; // not this
unsigned int y : 1; // not this
unsigned int z : 1; // not this

...use a single field such as:

unsigned int flags; // do this

...and assign every value to a bit; for example:

enum { // do this
  FLAG_X = (1 << 0),
  FLAG_Y = (1 << 1),
  FLAG_Z = (1 << 2),
  ALL_FLAGS = 0x07 // "all bits are on"
};

Then, to test "all false" you simply say "if (!flags)" and to test "all true" you simply say "if (flags == ALL_FLAGS)" where ALL_FLAGS is a number that sets all valid bits to 1. Other bitwise operators can be used to set or test individual bits as needed.

Note that this technique has an upper limit of 32 Boolean values before you have to do more (e.g. create an additional integer field to store more bits).

like image 44
Kevin Grant Avatar answered Jan 11 '23 11:01

Kevin Grant