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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With