Why did my tool throw a MISRA error here?

前端 未结 4 1675
死守一世寂寞
死守一世寂寞 2021-01-18 16:18

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 implici

4条回答
  •  迷失自我
    2021-01-18 16:41

    The MISRA rule is trying to ensure that the "underlying type" used for calculation is the same as the resulting type. To achieve that, you can cast the one, or both, of the operands:

    uint8_t rate = 3U; 
    uint8_t percentage = 130U;      
    uint16_t basic_units = (uint16_t)rate * percentage;
    

    On a 32-bit architecture the result without the cast is OK, however, consider the following:

    uint32_t rate =  ...;
    uint32_t percentage = ...;
    uint64_t basic_units = rate * percentage;
    

    On a 32-bit architecture, the operation will be performed in 32 bits - even though the target type is 64 bits wide. Where rate and percentage are large enough, this could result in the operation wrapping in 32 bits and so data that would have fit in the target type will be lost.

    The MISRA rule is attempting to make the code safer irrespective of the size of the types on the target platform.

提交回复
热议问题