Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with flags

Tags:

c++

algorithm

Let say I have an array of bool flags, it would be set to true or false depends on the condition.

Let say the index 1 ,2 ,6 have been set and all other flags are not set, I need to call functionA, and if index 2,3, 5 have been set and all other flags are not set, I need to call functionB. Is there an easy way where I could perform the logic above other than doing this:

if(array[1] == true && array[2] == true && array[6] == true && 
   array[3] == false && array[4] == false && array[5] == false)
{
  functionA();
}
like image 624
leslieg Avatar asked Nov 30 '22 04:11

leslieg


2 Answers

Maintenance and readability nightmare!

Consider this instead:

bool temperature_sensor_tripped(const bool_array& flags)
{
     return flags[1];
}

// [...]

if (temperature_sensor_tripped(array) 
    && moisture_sensor_tripped(array)
    && !alarm_dispatched(array))
{
    functionA();
}

This has the advantage that moisture_sensor_tripped() and its kin can be called from other functions without you (or the maintainer) remembering the order of the flags.

like image 142
Johnsyweb Avatar answered Dec 05 '22 13:12

Johnsyweb


Suggestion:

bool truecondition = array[1] && array[2] && array[6];
bool falsecondition = !array[3] && !array[4] && !array[5];

if (truecondition && falsecondition)
{
//do something
}
like image 28
Tony The Lion Avatar answered Dec 05 '22 12:12

Tony The Lion