Tips and Tricks – Testing for Equivalence

Firmware bugs have a nasty habit of hiding in plain sight while to one degree or another being camouflaged and difficult to spot.  One of these bugs that nearly every developer has made at one time or another stems from a very simple typo that can be seen below:

Equivalence

This simple conditional statement serves the purpose of checking to see if the variable LaunchMissile is set to TRUE.  If it is then the program undoubtedly starts a launch sequence, something that no programmer wants to do accidentally.  Unfortunately this line of code is setting the variable to TRUE, making the if statement TRUE and causing the accidental launch of a missile.

How can simple equivalence typos like these that set a variable with = instead of checking against a value with == be avoided?  There is a unique trick that is recommended by MISRA C for just this type of occasion!  It involves cases where the equivalence check is being performed against a literal constant (or a #define of a literal constant since the use of “magic” numbers is not recommended).  The trick is to place the literal constant on the left side of the operator rather than on the right.  This can be seen below:

Equivalence1

When the conditional statement is written this way, a literal constant is now trying to be assigned a value of LaunchMissile and will result in a compiler error!  The typo of = instead of == is detected!  (Most likely the compiler will complain about an assignment to non-lvalue).  Upon examining the error the missing = can be added which now causes the constant to be compared to LaunchMissile and that is a valid operation!  The corrected statement is now:

Equivalence2

The compiler warning is removed and the bug has been detected!  By writing all conditional checks with literal constants in this way helps to ensure that a simple typo doesn’t ruin the day!  Resulting in more robust code and one less bug to have to worry about.

Leave a Reply

Your email address will not be published. Required fields are marked *