gpt4 book ai didi

c - 数据类型范围有限

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:51 28 4
gpt4 key购买 nike

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

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

我收到这个警告:警告:由于数据类型 [-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 的补码或符号和大小上不同!)。

关于c - 数据类型范围有限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55482670/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com