Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to testing for equality and inequality in embedded software:

Rule 8.6.a.) 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, as shown in the if-else example in section 8.2.

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 localize. By following this rule, the compiler can detect erroneous attempts to assign (i.e., = instead of ==) a new value to a constant.

Exceptions

None.

Exceptions

A static analysis tool shall be configured to raise an error or warning about all assignment statements where comparisons are ordinarily expected.

Comments:

Does rule 8.6.a apply to the relational operators (i.e., "greater than" and "less than") too, even though the danger of confusing "=" and "==" doesn't exist for these? That is, does this rule require if (x < 5) be written as if (5 > x)?

No. That is not required by this rule. When it comes to other types of comparisons, programmers or teams should do what they believe will be easiest to read and maintain.

What’s happening and how it’s done. Get in the know.

Sign up for our newsletter today!

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.