MISRA C++ rule 5-0-3 false positive warning

亡梦爱人 提交于 2019-12-05 19:07:17

You have found the relevant section. The type of the expression where the literal is located is unsigned, so the underlying type is the smallest one that can fit an unsigned value 32, meaning uint8_t. It would have the very same underlying type if the literal had been 32 without the U suffix (though that would violate other MISRA rules).

What MISRA is aiming for here is that in the specific expression uint32_t arg; ... arg % 32U there can never occur a dangerous implicit conversion. That being said, you can safely cast the literal to uint32_t and that should silence all warnings. Ensuring that there are no implicit type promotions in your code what-so-ever is good programming practice, no matter what MISRA says/doesn't say.

If the purpose of the static analyser is just to check for implicit promotions in general, then the warning is fine. If the purpose of your static analyser is to check for MISRA compliance, then it is a false positive.

The line arg % static_cast<uint32_t>(32U) should never yield any form of diagnostic, regardless of the purpose of the tool. That is certainly a false positive.

I think this warning may be a false positive because, despite the 32U being a uint8_t

32U is not a uint8_t on any platform. With integer literals the smallest type you can express is a int/unsigned int. According to cppreference nnnnU can be a unsigned int, unsigned long int, or unsigned long long int. It does pick the first type that the literal can be stored in so 32U is a unsigned int.

So if you want to guarantee that 32U is the same type as uint32_t then you need the cast on the right hand side.

32U is of type unsigned, which is potentially a distinct type from uint32_t. Contrary to your statement, it is never of type uint8_t

A unsigned is only guaranteed to be able to represent the values in the range 0 to 65535, although it is permitted to support a larger range. What it actually can represent is implementation-defined. However, it cannot be a uint8_t, since a uint8_t cannot represent the range required of an unsigned.

This means, practically, three possibilities are that unsigned may be a 16-bit type, a 32-bit type, or even a 64-bit type - and these are, respectively, smaller, the same size, or larger than a uint32_t.

The result of the expression arg % 32U may therefore be of type uint32_t (if unsigned is 16-bit), uint32_t (if unsigned and uint32_t are both the same 32-bit type), or unsigned (if unsigned is a 64-bit type). In the last case, a conversion from unsigned to uint32_t is required to initialise u32a.

Your static analyser is warning you of this potential variation of behaviours between systems.

So, no, it is not a false positive.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!