简体   繁体   English

在无法到达的代码中停止GCC换档警告

[英]Stop GCC out-of-range shift warning in unreachable code

Given: 鉴于:

#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;
}

On a platform where the sizes are equal I get this, with various version of GCC: 在大小相等的平台上,我得到了各种版本的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

The code block is not reachable when the types have an equal size, so the bad shift will never execute. 当类型的大小相等时,代码块将无法访问,因此错误移位将永远不会执行。 It will only execute if long is wider than int , in which case the shift will not be out of range for that type. 仅当long大于int时才执行,在这种情况下,移位不会超出该类型的范围。

How can we eliminate this annoying warning, with these constraints: 在以下限制条件下,我们如何消除这种烦人的警告:

  • I don't want to disable it globally because it is useful (when not falsely positive). 我不想在全局禁用它,因为它很有用(当不是错误肯定时)。

  • I don't want split the shift---that is, perform it as two consecutive left shifts which add to the desired shift size. 我不想拆分班次-也就是说,将其作为两个连续的左班次执行,以增加所需的班次大小。

  • I don't want to convert the if test into a preprocessor #if . 我不想将if测试转换为预处理器#if (This is easy to do in this case with INT_MAX and LONG_MAX , but troublesome in the actual program.) (在这种情况下,使用INT_MAXLONG_MAX很容易做到,但是在实际程序中很麻烦。)


Based on nm 's answer, I'm using something very similar to the following pattern: 基于nm的答案,我正在使用与以下模式非常相似的内容:

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

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

This pattern applied in my actual code suppresses the diagnostic, and the generated code doesn't change compared to not multiplying by condition . 在我的实际代码中应用的这种模式抑制了诊断,并且与未乘以condition相比,生成的代码没有改变。

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

我与nm处于同一条路径,但提出了以下内容,从语义上看,这可能是预期的内容(最大sizeof(int)个字节来自x)。

x <<= (sizeof(long) - sizeof(int))*CHAR_BIT;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM