Similar to what is the fastest algorithm for permutations of three condition? and Fastest way to find correct combination with set of 8 booleans
I have three boolean
values (called a
, b
, and c
), each of which has a different action based on which ones are true. There is one little odd situation here; if a
is false then c
must also be false. There are six possibilities, and this results in a rather long and ugly looking if
statement chain. Here's what I came up with:
if (a)
{
if (b)
{
if (c)
{
doAction1(); // a = true, b = true, c = true
}
else
{
doAction2(); // a = true, b = true, c = false
}
}
else
{
if (c)
{
doAction3(); // a = true, b = false, c = true
}
else
{
doAction4(); // a = true, b = false, c = false
}
}
}
else
{
if (b)
{
doAction5(); // a = false, b = true, c = false
}
else
{
doAction6(); // a = true, b = false, c = false
}
}
I would prefer if the code was readable and fast, meaning that I would prefer not to use any weird bitwise operations. This isn't a homework assignment, just a simplified version of part of a personal project.
You can always write
if (a && b && c)
{
action1 ();
}
else if (a && b && ! c)
{
action2 ();
}
else if (a && ! b && c)
{
action3 ();
}
else if (a && ! b && ! c)
...
Arguably having fewer nesting levels and fewer braces that are just noise makes it more readable. And you don't need the comments anymore.