【问题标题】:negative integer implicitly converted to unsigned type负整数隐式转换为无符号类型
【发布时间】:2012-04-23 08:33:35
【问题描述】:

如何设置/取消设置类似以下的枚举值。使用 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;
}

【问题讨论】:

标签: c gcc enums bit-fields


【解决方案1】:

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

这样的表达
o &= ~FOUR

等价于

o = o & ~FOUR

在 RHS 上,o 是无符号整数,~FOUR 是有符号整数,根据类型转换规则,有符号整数将转换为无符号整数。 ~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

【讨论】:

    猜你喜欢
    • 2015-03-18
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2013-05-20
    • 2021-02-14
    相关资源
    最近更新 更多