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!
It depends on how you define elegant.
So I;m going to go with my own definition:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With