Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule 10.1: Essentially Boolean operands with & or | bitwise operators
#2
MISRA C:2012 introduced the idea of essential types in order to provide stricter type checking. It was the intention that boolean objects should not be used where an operand is interpreted as a numeric value. It also prevents the user mistyping & when && was intended.

An essential Boolean object cannot be guaranteed to have the value 0 or 1. It is only guaranteed that 0 is treated as false and non-zero as true.
For example
Code:
(mybool)(isalpha(ch))
    // isalpha returns an unspecified non-zero int value for an alphabetic character
    // mybool is an essential boolean type

Therefore
Code:
if( (mybool)(isalpha('a')) &  (mybool)(isalpha('b'))  // may be True or False - implementation defined
  if( (mybool)(isalpha('a')) && (mybool)(isalpha('b'))  // always True

This applies to essentially boolean type such as C90 "typedef int mybool".
However, a cast to the C99 _Bool will result in a 0 or 1 value, e.g. "typedef _Bool mybool".
Posted by and on behalf of the MISRA C Working Group


Messages In This Thread

Forum Jump:


Users browsing this thread: 1 Guest(s)