如何为以下内容设置/取消设置枚举值。使用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;
}
答案 0 :(得分:6)
由于你的枚举不包含任何负整数常量,我猜GCC已经为你的枚举提供了unsigned
int类型。现在像
o &= ~FOUR
相当于
o = o & ~FOUR
在RHS上,o
是unsigned int,~FOUR
是signed int,按类型转换规则,signed int将转换为unsigned 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