给定混合C和C++程序中的下列定义:
//in a C file.
uint8_t GetSize()
{
return (uint8_t)something;
}
//in the header of the C++ file.
public:
MyClass(){};
private:
uint8_t index_m;以下两行都为我提供了一个静态工具(pc-lint) 警告573。
void MyClass::IncrementWithRollOver(void)
{
index_m = (index_m + 1) % GetSize(); // warning 573 : signed-unsigned mix with divide
}
void MyClass::DecrementWithRollOver(void)
{
index_m = (GetSize() - 1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide
}我试了很多次,但是没有一个能帮我摆脱这个警告,为什么?
index_m = (index_m + 1U) % GetSize(); // this one works
index_m = (GetSize() - 1U + index_m) % GetSize();// info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]
index_m = (uint8_t)(index_m + (uint8_t)1) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 732: loss of sign (assignment) ('int' to 'uint8_t' (aka 'unsigned char')
index_m = (uint8_t)(GetSize() - (uint8_t)1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]
index_m = (uint8_t)(index_m + (uint16_t)1) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 732: loss of sign (assignment) ('int' to 'uint8_t' (aka 'unsigned char')
index_m = (uint8_t)(GetSize() - (uint16_t)1 + index_m) % GetSize(); // warning 573 : signed-unsigned mix with divide, and: info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]多么痛苦的..。C!
这件事有什么快速解决办法?
在阅读了这些评论后,我也尝试过,但没有成功。
index_m = (uint8_t)(index_m + (uint32_t)1) % GetSize(); // works
index_m = (uint8_t)(GetSize() - (uint32_t)1 + index_m) % GetSize(); // info 834: operator '-' followed by operator '+' could be confusing without parentheses [MISRA 2004 Rule 12.1, advisory]这让我摆脱了符号/无符号混合问题,但是这个“操作符”-‘后面跟着操作符'+'“仍然很奇怪!
发布于 2019-07-22 15:02:04
在C/C++中,小于int的整数一旦在操作中使用(+.),就会被提升为具有相同符号的整数,并且与int一样大。
这是历史性的,也有点令人困惑,但我想最初的意图是限制使用小整数计算时溢出的风险。
在index_m + 1中,index_m将被提升为unsigned int,然后符号与1 (即signed int )不匹配。
因此,在操作完成后,您将不得不进行强制转换(取决于警告级别)。
https://stackoverflow.com/questions/57148717
复制相似问题