数据类型范围有限

limited range of data types

当我在 GCC 中编译这段代码时:

uint8_t *reg = ..., newflags = ...;
...
if(*reg == (~(uint8_t)0))
{
    newflags |= (1<<2);
    newflags |= (1<<7);
}

我收到此警告: warning: comparison is always false due to limited range of data type [-Wtype-limits]

regnewflags分别是uint8_t *uint8_t类型。

这是什么意思?我该怎么做才能解决它?

~(uint8_t)0 应该是 (uint8_t)~0。与其他算术运算符一样,~ 的操作数将扩展为 int(或 unsigned int 如果不是所有原始类型的值都可以在 int) 中表示,并且 int 0 的所有位都反转在 uint8_t 的范围之外,除非实现支持负零...引用holy book, 6.5.3.3p4的先前修订:

  1. The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

为了获得最大的兼容性,您应该使用 0U 而不是 0 以确保将值提升为 unsigned int 而不是 int,但极有可能您的计算机是 2 的补码计算机 - 特别是对于像 uint8_t 这样的固定宽度类型 - 并且 (uint8_t)~0 的行为将等同于 (uint8_t)~0U(在 1 的补码或符号和上可能不同-幅度!)。