Hello everyone. I still consider myself a newbie with coding C for the Arduino. My question is when I am evaluating a list of conditions, is there a better approach than using nested if statements? Let's say I am going to have 6 different conditions that all need to check true or false in order to run the code? For example, if I have 6 pushbuttons and they all need to be pushed for an LED to turn on.
Would I nest 6 if statements or is there a better or cleaner approach? I thought about using a case statement but I don't think that is what case statements were geared towards.
Is there any significant delay in processing time when evaluating if statements (providing the evaluation is simple such as if a pushbutton is pressed or not)?
Borrow from logic and if you can write the condition in one of the following ways do so
if (a && b && c && d && e && f) // conjuction (ands)
{
..
}
if (a || b || c || d || e || f) // disjunction (ors)
{
..
}
if (a || (b && c) || d || (e && f && g)) // disjunctive normal form (or of ands)
{
..
}
if ((a || b) && c && (d || e) && f) // conjunctive normal form (and of ors)
{
..
}
Possibly with a negation at the top (since C only has "if" and not "unless" keyword).
Break complex conditions into several lines to make them easier to read (applies
especially to the latter two forms).
More complex than that suggests nesting or - better - function/predicate abstraction is best
(that means stuffing some of the tests in a subfunction that is meaningful in its own right).
In general if the test is complex to do but is conceptually easy to explain, put it in
a function with a well-chosen name:
if (in_safe_state ())
{
..
}
..
boolean in_safe_state ()
{
if (motor_active ())
return false ;
if (mode == IDLE)
return true ;
..
..
}