简体   繁体   中英

Using enum members with enum name in C

I have defined the following enum:

typedef enum {
    F105 = 0x00,
    F164 = 0x10,
    F193 = 0x20,
    F226 = 0x30,
    F227 = 0x40
}BOARD_TYPE;

To make the code readable, I would like to use the enum name when using one of its members. Like this:

void do_work(uint8_t board_type) {
    if (board_type == BOARD_TYPE.F164) {
        // Do stuff...
    }
}

Now, this doesn't compile. I get an error message "Expected expression before 'BOARD_TYPE'".

So what would be the proper way of using a enum member while also referring to the enum name to increase code readability?

enum is a list of values, an "enumeration". It is not a struct/container class with members.

Now what you should do for clarity is to only compare enumeration constants of a given type with variables of the same type. Not against uint8_t as in your example.

This is pretty much self-documenting code:

void do_work (BOARD_TYPE board_type) {
    if (board_type == F164) {
        // Do stuff...
    }
}

Good compilers can be configured to give warnings when comparing enums against wrong types. Otherwise you can also create type safe enums with some tricks.

You can also prefix all enum constants to indicate what type they belong to - this is common practice:

typedef enum {
    BOARD_F105 = 0x00,
    BOARD_F164 = 0x10,
    BOARD_F193 = 0x20,
    BOARD_F226 = 0x30,
    BOARD_F227 = 0x40
}BOARD_TYPE;

enum is not a structure and the member names are just names of the corresponding constants so you cant access enums elements via .

Change

BOARD_TYPE.F164

to

F164

enum constants are of type int so board_type will expand to int .


For better readability

typedef enum {
    BOARD_F105 = 0x00,
    BOARD_F164 = 0x10,
    BOARD_F193 = 0x20,
    BOARD_F226 = 0x30,
    BOARD_F227 = 0x40
}BOARD_TYPE;

Its always better to pass an enum type like

// Function definition
void do_work(BOARD_TYPE board_type) {
    if (board_type == BOARD_F164) {
        // Do stuff...
    }
}

// Calling
do_work(BOARD_F164);

enum s in C aren't classes like they are in Java. In general, you can't qualify the name of an enum with its type. That's why this fails:

typedef enum {
  F227 = 0x40 } BOARD_TYPE;

typedef enum {
  F227 = 0x40 } BOARD_TYPE2;

It's a little ugly, but I think the only way to get around this problem is to use the type in the name:

typedef enum {
  BOARD_TYPE_F227 = 0x40 } BOARD_TYPE;

Just use the enumeration value. Additionally you can use the enum-type as function parameter.

void do_work(BOARD_TYPE board_type) {
    if (board_type == F164) {
        // Do stuff...
    }
}

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