What can I do to avoid MISRA giving this error for the code below? I tried casting with (unit16_t). But then it didn’t allow an explicit conversion.
Illegal implicit conversion from underlying MISRA type “unsigned char” to “unsigned int” in complex expression (MISRA C 2004 rule 10.1)
uint8_t rate = 3U; uint8_t percentage = 130U; uint16_t basic_units = rate * percentage;
The problem is that both rate and percentage are silently promoted by the integer promotions to type “int”. The multiplication is therefore performed on a signed type.
MISRA compatible code is to either rewrite the code as
or do as MISRA suggests, immediately typecast the result of an expression to its “underlying type”:
EDIT: Clarification follows.
Informative text from MISRA-C:
I’m actually not sure whether the 2nd line of mine above would satisfy MISRA or not, at second thought I may have confused MISRA 10.1 with 10.5, where the latter enforces an immediate cast to underlying type, but only in case of certain bitwise operators.
I tested both lines with LDRA static code analysis and it didn’t complain (but gives some incorrect, non-related warnings), but then LDRA also performs very poorly at MISRA-C.
Anyway, the problem in the original question is that rate and percentage are both implicitly converted by the integer promotions to type int which is signed, since int can represent all values of a uint8_t. So it becomes
To prevent this you have to typecast explicitly. After giving it more thought, I’d go with the 1st line of my two above.