Rules 11 through 15 of Netrino's list of bug killers for firmware coding include how to deal with global variables and keywords. Michael Barr also weighs in on brace style.
Rule #15: When evaluating the equality or inequality of a variable with a constant value, always place the constant value on the left side of the comparison operator.
Example (do):
if (0 == x){ /* Do this only if x is zero. */}
Reasoning: It is always desirable to detect possible typos and as many other bugs as possible at compile-time; run-time discovery may be dangerous to the user of the product and require significant effort to locate. By following this rule, the compiler can detect erroneous attempts to assign (i.e., = instead of ==) a new value to a constant.2
Try adding some or all of the fifteen practical embedded C coding rules from this and last month's column to your coding standard to keep bugs out of your embedded system.
?183-142?
Michael Barr is the author of two books and more than forty articles about embedded systems design, as well as a former editor-in-chief of this magazine. Michael is also a popular speaker at the Embedded Systems Conference and the CTO of Netrino. E-mail him at mbarr@netrino.com or read more of what he has to say at www.embeddedgurus.net/barr-code.
Endnotes:
1. Full disclosure: Netrino is my employer and our Embedded C Coding Standard is something we developed first for internal use but now also sell as a book.
2. But remember, floating-point values should never be compared to constants. A number like 0.1x10-15 is not strictly equal to zero.