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();
}
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.
Suggestion:
bool truecondition = array[1] && array[2] && array[6];
bool falsecondition = !array[3] && !array[4] && !array[5];
if (truecondition && falsecondition)
{
//do something
}
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