C:给枚举赋负值?

C : assign negative value to enum?

背景

我试图将-1分配给枚举变量,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
typedef enum test {
        first,
        second,
}soc_ctr_type_t

soc_ctr_type_t ctype;

...

switch(type){
   case 1:
       ctype = first;
   break;

   case 2:
      ctype = second;
   break;

   default:
      ctype = -1;
}

如果type是默认情况,则ctype应该变为-1,但不是。
当我使用printf进行调试时,ctype为255.

为什么ctype变为255而不是-1?


在枚举器列表中定义具有该值的枚举器,结果将是正确的:

1
2
3
4
5
typedef enum test {
        minus_one = -1 ,
        first,
        second,
} soc_ctr_type_t;

看到255的原因是因为编译器为此枚举器选择了较窄的无符号类型,因为它可以看到的所有firstsecond值均为0、1。因此,选择的类型是unsigned char,因为它可以表示这两个值。
此类型将从-1换为255。

C中的枚举数不是特殊类型,它们由整数类型表示,因此您可以为枚举数列表中不存在的枚举数指定一个值。


在这里添加2501即可。

The underlying type of an enumeration is an integral type that can
represent all the enumerator values defined in the enumeration. It is
implementation-defined which integral type is used as the underlying
type for an enumeration except that the underlying type shall not be
larger than int unless the value of an enumerator cannot fit in an int
or unsigned int.

另一个好读C枚举是签名的还是未签名的?