I've been working with some code to ensure MISRA compliance. The issue with this piece of code is
Operands shall not be of an inappropriate essential type. The operand of the ? operator is of an inappropriate essential type category unsigned.
I assume the issue is with the first argument being an unsigned data type, instead of boolean, which means the fix bellow would work.
The original,
return (uint32Var & 0x80000000u) ? 0u : 1u;
My change to the code,
return ( (uint32Var & 0x80000000u)!=0u ) ? 0u : 1u;
Is this a correct change to make? I'm concerned about changing the functionality of the code but as far as I know, at least in if logic, the operand is evaluated as numVar != 0
inside the if ( numVar )
operator.
That is safe.
You'll be comparing the unsigned 32-bit:
(uint32Var & 0x80000000u)
To the unsigned int
:
0u
Usual arithmetic conversions apply to ensure that regardless of the actual types involved here, you'll be comparing values of types that are at least large enough to contains unsigned 32-bit.
The value (uint32Var & 0x80000000u)
is a false one if it is equal to 0
, otherwise it is a true one. Comparing the value to 0
has the effect, and yielding 0
if the comparison is equal, otherwise yielding 1
is equivalent behavior.
As another note, the value that you end up using for the first operand of the ternary operator isn't a bool
, it's an int
. The !=
operator yields an int
value of either 0
or 1
.