我有以下代码:
const uint8_t HEADER_SIZE = 0x08;
std::vector<uint8_t> a, b;
uint8_t x;
/* populate 'a', 'b'. Set 'x' */
for ( uint8_t i = 0; i < HEADER_SIZE; ++i )
{
// The if statement (specifically the AND): Conversion to 'unsigned int' from 'int' may change the sign of the result [-Wsign-conversion]
if ( x != ( a[i + HEADER_SIZE] & b[i] ) )
{
/* ... */
break;
}
}
我尝试了几乎所有的转换,但我似乎无法弄清楚为什么一个简单的 AND 会导致此警告。两个变量都是无符号的。有什么想法吗?
最佳答案
a[i + HEADER_SIZE]
和 b[i]
都将被提升为 int
,因为尽管它们都是无符号类型,但它们是比 int
更窄的类型。所有较窄的整数类型都被提升为 int
(如果 int
可以表示被提升类型的所有值)或 unsigned int
用于所有构建在算术运算中。
将所有操作数显式转换为 unsigned int
应该消除警告:
unsigned int a_dash = a[i + HEADER_+SIZE];
unsigned int b_dash = b[i];
unsigned int x_dash = x;
if (x_dash != (a_dash & b_dash))
{ // ...
关于c++ - 添加和比较时签署约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675722/