[C-safe-secure-studygroup] Rule 10.4 review

Martin Sebor msebor at gmail.com
Wed Aug 23 15:27:11 UTC 2017


Rule 10.4 - Both operands of an operator in which the usual
arithmetic conversions are performed shall have the same
essential type category.

The rule depends on MISRA's concept of /essential type category/
and requires that operands in binary and ternary expressions have
the same essential type.  For example, if one is signed the other
has to be signed as well.  Or when one is an enum the other has
to be of the same enum type.

I have a couple of concerns with this rule.

First, it declares non-compliant many safe expressions involving
integer literal constants, such as:

   unsigned i = 0;
   ...
   f (i + 2);

or

   if (i == 2);

because the essential type category of i is unsigned and that
of 2 is signed.  Instead, it requires to explicitly specify
the signedness of the constant:

   i += 2U;

or

   if (i == 2U);

In my opinion that's unnecessary and would result in many false
positives for existing correct code.

Second, it makes relational or equality expressions involving
enums non-compliant that compare their values against integer
constants expressions that result from bitwise AND or bitwise
OR of the enumerators of the same types.  For instance:

   enum Color { Red = 1, Green = 2, Blue = 4 } clr;

   bool is_white = clr == (Red | Green | Blue);

This kind of code isn't uncommon so the restriction would force
it to change.  I don't have a sense of how much of a burden that
might be or whether the benefits of the increased type safety
would justify them.

In light of these concerns I would be uneasy about recommending
the rule in its present form for adoption in the standard.  That
said, there are aspects of it that are worth considering.  With
the issues involving literals and enums resolved a similar rule
would be worth considering (checkers along these lines have been
implemented in popular compilers; e.g., GCC's -Wconversion).

Martin



More information about the C-safe-secure-studygroup mailing list