2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
user145760
  • 124
  • 9
  • You could avoid the ternary operator altogether, e.g. `return 0 == (uint32Var & 0x80000000u);`. (I have no idea if that complies with the MISRA(ble) rules.) – Ian Abbott Jul 23 '19 at 12:16

2 Answers2

1

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.

Thomas Jager
  • 4,836
  • 2
  • 16
  • 30
0

I assume the issue is with the first argument being an unsigned data type, instead of boolean, which means the fix bellow would work. /--/

Is this a correct change to make?

Yes. As in, it will make the code MISRA compliant. The warning is indeed about using a non-boolean type for the 1st operand.

However, assuming that the function returns uint32_t, you may as well just write:

return (uint32_t) !(uint32Var & mask);

(mask since MISRA, like everyone else, discourages the use of "magic numbers".)

Equivalent and also MISRA-C compatible:

return ~uint32Var >> bits; // where bits in this case is 31

Normally the ~ operator is a nasty piece when writing MISRA compilant code, but it is perfectly safe when you use an unsigned integer type which is not a small integer type, such as uint32_t.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396