簡體   English   中英

在無法到達的代碼中停止GCC換檔警告

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

鑒於:

#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

當類型的大小相等時,代碼塊將無法訪問,因此錯誤移位將永遠不會執行。 僅當long大於int時才執行,在這種情況下,移位不會超出該類型的范圍。

在以下限制條件下,我們如何消除這種煩人的警告:

  • 我不想在全局禁用它,因為它很有用(當不是錯誤肯定時)。

  • 我不想拆分班次-也就是說,將其作為兩個連續的左班次執行,以增加所需的班次大小。

  • 我不想將if測試轉換為預處理器#if (在這種情況下,使用INT_MAXLONG_MAX很容易做到,但是在實際程序中很麻煩。)


基於nm的答案,我正在使用與以下模式非常相似的內容:

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);

我與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