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

1 回答 1

6

由于您的枚举不包含任何负整数常量,我猜 GCC 已将unsignedint 类型赋予您的枚举。现在的表达式像

o &= ~FOUR

相当于

o = o & ~FOUR

在 RHS 上,ois unsigned int 和~FOURissigned int 并按类型转换规则,将signed int 转换为 unsigned int。也是~FOUR一个负数,因此您会收到将负数隐式转换为无符号类型的警告。

如果您确定自己的逻辑,则不必担心警告,或者您可以通过使用enum等于负数的虚拟变量将枚举转换为带符号的。

就像是

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

此外,您的代码存在运行时缓冲区溢出问题。在函数byte_to_binary中,您正在检查 9 位,但您的缓冲区也是 9 个字节。它必须是 10 个字节,一个用于终止空值。做到这一点static char b[10];,一切正常

于 2012-04-23T08:59:25.860 回答