2012-04-23 108 views
0

如何設置/取消設置類似於以下內容的枚舉值。使用GCC,我得到這個惱人的警告:隱式轉換爲無符號類型的負整數

test.c:37: warning: negative integer implicitly converted to unsigned type 
test.c:39: warning: negative integer implicitly converted to unsigned type 
test.c:41: warning: negative integer implicitly converted to unsigned type 
test.c:43: warning: negative integer implicitly converted to unsigned type 

代碼:

#include <stdio.h> 
#include <string.h> 

typedef enum { 
ONE = 0x1, 
TWO = 0x2, 
THREE = 0x4, 
FOUR = 0x8, 
} options; 

static const char *byte_to_binary (int x) 
{ 
    int z; 
    static char b[9]; 
    b[0] = '\0'; 

    for (z = 256; z > 0; z >>= 1) 
    { 
    strcat(b, ((x & z) == z) ? "1" : "0"); 
    } 

    return b; 
} 

int main(int argc, char *argv[]) 
{ 
    options o = 0; 
    printf("%s\n", byte_to_binary(o)); 
    o |= ONE; 
    printf("%s\n", byte_to_binary(o)); 
    o |= TWO; 
    printf("%s\n", byte_to_binary(o)); 
    o |= THREE; 
    printf("%s\n", byte_to_binary(o)); 
    o |= FOUR; 
    printf("%s\n", byte_to_binary(o)); 
    o &= ~FOUR; 
    printf("%s\n", byte_to_binary(o)); 
    o &= ~THREE; 
    printf("%s\n", byte_to_binary(o)); 
    o &= ~TWO; 
    printf("%s\n", byte_to_binary(o)); 
    o &= ~ONE; 
    printf("%s\n", byte_to_binary(o)); 

    return 0; 
} 
+1

請顯示行號。 – 2012-04-23 08:38:06

+0

這可能會有所幫助:http://stackoverflow.com/questions/2579230/signedness-of-enum-in-c-c99-c-cx-gnu-c-gnu-c99 – bmartins 2012-04-23 08:41:24

回答

6

由於您的枚舉不包含任何負面的整型常量,我想GCC給unsigned整型到您的枚舉。現在像

o &= ~FOUR 

的表達式是等效於

o = o & ~FOUR 

在RHS,o是無符號的int和~FOUR簽署int和通過類型轉換規則,符號int將被轉換爲無符號整型。另外~FOUR是負數,因此您會收到警告,將負數隱式轉換爲無符號類型。

如果您確定自己的邏輯,則不必擔心警告,或者您可以將枚舉轉換爲帶有虛擬enum(等於負數)的符號。

喜歡的東西

typedef enum { 
DUMMY =-1, 
ONE = 0x1, 
TWO = 0x2, 
THREE = 0x4, 
FOUR = 0x8, 
} options; 

此外,您的代碼運行時buffer overflow problems。在功能byte_to_binary你正在檢查9位,但你的緩衝區也是9個字節。它必須是10個字節,一個用於終止空值。做它static char b[10];和一切works fine

相關問題