c++ - MISRA C++ 规则 5-0-3 误报警告

标签 c++ misra

我的静态分析器发出以下警告:

MCPP Rule 5-0-3: This complex expression is implicitly converted to a different essential type

对于以下代码:

void func(const uint32_t arg)
{
    //32U has underlying type uint8_t
    const uint32_t u32a = arg % 32U; //warning issued in this line
    const uint32_t u32b = (arg % static_cast<uint32_t>(32U)); //same warning issued in this line
    const uint32_t u32c = static_cast<uint32_t>(arg % 32U); //compliant
}

根据MISRA底层类型转换规则:

Otherwise, if both operands have integral type, the underlying type of the expression can be found using the following:

– If the types of the operands are the same size, and either is unsigned, the result is unsigned.

– Otherwise, the type of the result is that of the larger type.

我认为这个警告可能是误报,因为尽管 32Uuint8_t,表达式应该采用较大类型的基础类型,在这种情况下uint32_t,因此不需要 static_cast

您是否同意这是误报?还是我看错了?

编辑: MISRA 标准规定:

The underlying type of an integer constant expression is therefore defined as follows:

  1. If the actual type of the expression is signed integral, the underlying type is defined as the smallest signed integer type that is capable of representing its value.

  2. If the actual type of the expression is unsigned integral, the underlying type is defined as the smallest unsigned integer type that is capable of representing its value.

  3. In all other circumstances, the underlying type of the expression is defined as being the same as its actual type.

没有。 2 是我必须假设 32U 的基础类型为 uint8_t 的原因。

最佳答案

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

32U 在任何平台上都不是 uint8_t。对于整数文字,您可以表达的最小类型是 int/unsigned intAccording to cppreference nnnnU 可以是 unsigned intunsigned long intunsigned long long int。它确实选择了可以存储文字的第一种类型,因此 32U 是一个 unsigned int

因此,如果您想保证 32Uuint32_t 的类型相同,那么您需要在右侧进行强制转换。

关于c++ - MISRA C++ 规则 5-0-3 误报警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206493/

相关文章:

c - 符合 MISRA 标准的运行时字节顺序检测

c - 需要对 MISRA 规则 13.6 进行解释

c - MISRA 相当于医疗行业?

c++ - C/C++ 条件返回语句

c - sprintf 的 MISRA 兼容替代品?

c++ - Mat name[x] 到底给出了什么?

c++ - 寻找最佳方法背后的逻辑

java - 最好的日志文件格式是什么?

c++ - CMake,当使用 FindFoo.cmake 或 FooConfig.cmake (和其他说明)

c++ - 如何防止 cvLoad 失败?