verify that only 1 out of 4 booleans is true

In my program I have defined 4 booleans

bool A
bool B
bool C
bool D

they are independently set 'true' or 'false' based on certain conditions.

At the end of the loop only one of them should be 'true', the other 3 should be 'false'.

What is the most elegant way to verify that only 1 out of 4 booleans is true ?

What do you get if you sum A, B, C and D ?

What do you get if you sum A, B, C and D ?

After you 'cast' them to integers, or at least make sure the addition happens as integers (you can add them to an integer initialized as '0') ?

you can add them to an integer initialized as ‘0’

Whilst agreeing that my suggestion was “naughty” and that the booleans should be cast or changed to ints, why would you add 48 to the sum ?

why would you add 48 to the sum ?

I mean zero not the character '0'. You know that.

True, I guessed that but will @gammakappa ?

Why would you add ‘0’?
Surely the debug print routine will do that for you?

OP, I would be looking at this from a different point of view. If the "certain conditions" are supposed to only allow one of A, B, C or D to be set true, yet somehow it's possible for there to be more than one set (else you wouldn't have posted here) then I'd say you should make your logic more robust in the first place.

In a sense, (and I say this of course with no knowledge of your system) it's "too late" to check after the fact that more than one is set. You say the 4 flags are independent, yet the fact that only one should be set means there is some level of dependence, and I would investigate the logic that somehow allows more than one to get set.

if ((A?1:0)+(B?1:0)+(C?1:0)+(D?1:0) != 1) ...

That is what I had in mind when I said

the booleans should be cast or changed to ints

earlier in the thread but I am not sure that the OP is ready for it

My original quick-and-dirty solution was :

int SanityCheck=0; 
  if (A == true) {  SanityCheck++;  }
  if (B == true) {  SanityCheck++;  }
  if (C == true) {  SanityCheck++;  }
  if (D == true) {  SanityCheck++;  }
  if (SanityCheck !=1) { // raise error }

PaulRB’s proposal:

if ((A?1:0)+(B?1:0)+(C?1:0)+(D?1:0) != 1)

is more or less what I was looking for.
It’s compact although it is less ‘human readable’ with my level of coding experience :grin: .

Thanks all.

if (A == true) { SanityCheck++; }If A is a boolean, the “== true” is redundant.

Sanity check += A ? 1:0; :smiley:

Why would you add '0'?

The idea was

int total = 0;
total = total + a + b + c + d;

where the integer assures that the addition is done as an integer, but i guess if you cast the first boolean you can achieve the same thing.int total = (int) a + b + c + d;

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.