gpt4 book ai didi

c - 在无法访问的代码中停止 GCC 超出范围的移位警告

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:06 25 4
gpt4 key购买 nike

给定:

#include <stdio.h>
#include <limits.h>

int main()
{
if (sizeof (long) > sizeof (int)) {
long x = 42;
x <<= CHAR_BIT * sizeof (int);
}

printf("sizeof (long) == %d\n", (int) sizeof (long));
printf("sizeof (int) == %d\n", (int) sizeof (int));

return 0;
}

在大小相等的平台上,我得到了这个,使用了不同版本的 GCC:

$ gcc -Wall shiftcomplain.c  -o shiftcomplain
shiftcomplain.c: In function ‘main’:
shiftcomplain.c:8:5: warning: left shift count >= width of type [enabled by default]
$ ./shiftcomplain
sizeof (long) == 4
sizeof (int) == 4

当类型大小相等时,代码块不可到达,因此错误的转换将永远不会执行。它只会在 longint 宽时执行,在这种情况下,移位不会超出该类型的范围。

在这些限制条件下,我们如何消除这个烦人的警告:

  • 我不想全局禁用它,因为它很有用(当不是误报时)。

  • 我不想拆分移位——也就是说,将其作为两个连续的左移位来执行,这会增加所需的移位大小。

  • 我不想将 if 测试转换为预处理器 #if。 (在这种情况下使用INT_MAXLONG_MAX很容易做到,但在实际程序中很麻烦。)


根据 n.m. 的回答,我使用了与以下模式非常相似的内容:

const int condition = sizeof (long) > sizeof (int);

if (condition) {
/*...*/
x <<= CHAR_BIT * sizeof (int) * condition;
}

在我的实际代码中应用的这种模式抑制了诊断,与未乘以 condition 相比,生成的代码没有改变。

最佳答案

x <<= (sizeof (long) > sizeof (int) ? CHAR_BIT * sizeof (int) : 0);

关于c - 在无法访问的代码中停止 GCC 超出范围的移位警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34108532/

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