If the operator for multiple scenarios
I am struggling to complete this if statement. There must be an easier way to go through all the combinations, because it might not be good practice.
if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)
I wonder if I want to go through all the combinations, is there any other way to do this rather than duplicating the expression?
source to share
One way is to convert the values one
, two
both three
to one int
with the correct bits set and using instructions switch
for binary masks, for example:
int combined=0;
// Construct a binary representation using your Boolean values as bits:
// Value of one goes to bit zero
if (one) combined |= (1 << 0);
// Value of one goes to bit one
if (two) combined |= (1 << 1);
// Value of three goes to bit two
if (three) combined |= (1 << 2);
switch (combined) {
case 0: // All false
break;
case 1: // one is true, other are all false
break;
...
case 7: // All true
break;
}
All eight combinations are now encoded as integer values:
int three two one
_-- ----- --- ---
0 - 0 0 0
1 - 0 0 1
2 - 0 1 0
3 - 0 1 1
4 - 1 0 0
5 - 1 0 1
6 - 1 1 0
7 - 1 1 1
It goes without saying that you need to heavily comment on such code for readers of your code who have not memorized the binary representations of small numbers.
source to share
You can do something like:
int i = (one ? 1 : 0) | (two ? 2 : 0) | (three ? 4 : 0);
switch(i)
{
case 0:
// ...
case 1:
// ...
case 7:
// ...
}
It will be very fast - it will be a direct branch ( opcodeswitch
) and expressions will only be evaluated once.
source to share
You don't need one != true
the second line as you have already eliminated the case where everything is correct. You can simplify this usage:
if (one && two && three) {
}
else if (one && two) {
}
else if (two && three) {
}
else if (one && three) {
}
else if (one) {
}
else if (two) {
}
else if (three) {
}
else
{
// none true
}
source to share
The best way to do this is to have each of these elements declared as bool. This way you can delete all lines == ?
and have something like this:
bool one = true; // Random decision to call it true, just for testing
bool two = false;
bool three = true;
if(one && two && three)
// Do something
else if(!one && two && three)
// Do something else.
source to share