简体   繁体   中英

Assigning invalid value for a typedef enum variable

I remember reading somewhere in SO saying if:

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 would actually make it assign to unknown is not correct (as already pointed by 'Oli').

An enumeration consists of a set of named integer constants. 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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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