这是代码:
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]
为什么?以及如何避免这种情况?
您正在比较默认情况下x
哪个是哪个。因此,您得到了隐式二进制转换。unsigned short
1
int
给你的编译器一个提示,你实际上想x
与另一个unsigned
值进行比较:
if ((x==1U) && y)
因为 1 被视为 int。利用
unsigned int x
或投
尝试这个
if ( ( static_cast<unsigned int>(1) == x ) && y)
目前尚不清楚您使用的是哪个版本的 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
学习整数提升和通常的算术转换。