简体   繁体   English

为 typedef 枚举变量分配无效值

[英]Assigning invalid value for a typedef enum variable

I remember reading somewhere in SO saying if:我记得在 SO 的某处读到,如果:

typedef enum TEST {
   zero,
   one,
   two,
   unknown
};

Then, doing a TEST test1 = 5 would actually make it assign to unknown value, in this case would be 3. I've wrote and tested but it didn't assign to that value, so what's the used of having an unknown value at the end of the enum?然后,执行TEST test1 = 5实际上会将其分配给unknown值,在本例中为 3。我已经编写并测试过但它没有分配给该值,那么在枚举的结尾?

TEST test1 = 5 would actually make it assign to unknown is not correct (as already pointed by 'Oli'). TEST test1 = 5 would actually make it assign to unknown不正确(正如'Oli'已经指出的那样)。

An enumeration consists of a set of named integer constants.枚举由一组命名的 integer 常量组成。 A variable with enumeration type stores one of the values of the enumeration set defined by that type.具有枚举类型的变量存储由该类型定义的枚举集的值之一。 Although it is desirable to have one of the pre-defined values, but assigning some other random value isn't illegal .虽然希望有一个预定义的值,但分配一些其他随机值isn't illegal的。

Most (not all) of the times, enum constants are used for examining some parameter which is expected to have some pre-defined range of values.大多数(不是全部)时间,枚举常量用于检查一些参数,这些参数预期具有一些预定义的值范围。 For eg: in a network application, you may have to send some msg_id (which is enum constant) with every message from one end and take some action based on this msg_id at the other end.例如:在网络应用程序中,您可能必须在一端的每条消息中发送一些 msg_id(它是枚举常量),并在另一端基于此 msg_id 采取一些行动。 However, if the received msg_id is not one of the pre-defined values for enum, you can set msg_id = Unknown and return an error.但是,如果接收到的 msg_id 不是 enum 的预定义值之一,您可以设置msg_id = Unknown并返回错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM