Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ideal If statement structure for two boolean values

I wasn't quite sure what to search under - but I was looking for an elegant way if possible to structure an if statement that uses two Boolean values that could easily output all four possibilities.

Variables:

bool a = true;
bool b = true;

I wasn't sure if there was a best practice in terms of checking both for negativity - then continuing on etc.

Very hastily written example:

if(!a && !b)
{
   //Output (-,-)
}
else
{
   if(a || b)
   {
       if(a)
       {
           //Output (+,-)
       }
       else
       {
           //Output (-,+)
       }
   }
   else
   {
       //Output (+,+)
   }
}

Sorry for all the gullwings ( { } ) I am a bit of a formatting junkie. Anyways - thanks for any suggestions!

like image 875
Rion Williams Avatar asked Oct 31 '25 19:10

Rion Williams


2 Answers

It depends on how you define elegant.

So I;m going to go with my own definition:

  1. Symmetric.
  2. Readable.
  3. Avoids unnecessary complexity.

With that in mind, I'd just go for:

if( a ) {
  if( b ) {
     ...
  } else {
     ...
  }
} else {
  if( b ) {
     ...
  } else {
     ...
  }
}

It isn't any less verbose than your idea but at least it's crystal clear what is meant there.

Having said that, I find control structures like this highly suspicious. You can probably either:

  1. Use a (two-dimensional) constant array to fetch a value, if all you do is assign a value to a variable.
  2. Rephrase the whole block to avoid redundantly calling similar code. Maybe factor out one of the checks into a function.
  3. You may not need two separate booleans at all, a single variable with 4 possible values would be more expressive and you could then use a switch/case structure.
like image 95
biziclop Avatar answered Nov 02 '25 13:11

biziclop


I'm not fully sure I get what you're asking... do you just want an if statement to cover all four possibilities?

If so, here's one simple way to do this:

if (a && b)
    // Output (+, +)
else if (!a && b)
    // Output (-, +)
else if (a && !b)
    // Output (+, -)
else
    // Output (-, -)

If this isn't what you're looking for, let me know and I'll take down this post.

like image 37
templatetypedef Avatar answered Nov 02 '25 13:11

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!