2

这是代码:

test.cpp

unsigned short x;
bool y;
if ((x==1)&& y)
{
  ...
}
else
{
  ...
}

我收到一条 lint 消息:

Note 912 Implicit binary conversion from int
to unsigned int [MISRA Rule 48]

为什么?以及如何避免这种情况?

4

4 回答 4

2

您正在比较默认情况下x哪个是哪个。因此,您得到了隐式二进制转换。unsigned short1int

给你的编译器一个提示,你实际上想x与另一个unsigned值进行比较:

if ((x==1U) && y)

于 2016-02-01T08:53:06.397 回答
0

因为 1 被视为 int。利用

unsigned int x 

或投

于 2016-02-01T07:10:10.067 回答
0

尝试这个

if ( ( static_cast<unsigned int>(1) == x ) && y)
于 2016-02-01T06:06:08.913 回答
0

目前尚不清楚您使用的是哪个版本的 MISRA。在编写 C++ 代码时,您应该使用 MISRA-C++,否则将违反 MISRA 规则。显然不能用 MISRA-C 检查器检查对 MISRA-C++ 的合规性。

无论如何,假设您有一个具有 32 位整数的系统,无论 MISRA 版本如何,这都应该可以解决问题:

if ( ( static_cast<uint32_t>(x) == 1u ) && y)   // compliant

要理解的重要部分是隐式促销如何工作以及如何避免它们:

  • 1文字转换为unsigned short不会解决任何问题。int这样的强制转换完全是多余的,因为无论如何操作数都会立即得到整数提升。

    if ( ( x == static_cast<unsigned short>(1) ) && y) // not compliant

    unsigned short ushort=1u; if ( ( x == ushort ) && y) // not compliant

  • 1文字转换为unsigned int或仅将其更改为1u(相同的东西)将使程序按预期运行,但不会解决 MISRA 警告。因为您仍然有x操作数的隐式类型提升,这是 MISRA 违规。

    if ( ( x == 1u ) && y) // not compliant

    if ( ( static_cast<unsigned int>(1) == x ) && y) // not compliant

学习整数提升通常的算术转换

于 2016-02-09T10:50:20.687 回答