Reputation: 1322
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?
Upvotes: 2
Views: 3727
Reputation: 4307
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;
Upvotes: 1
Reputation: 6465
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);
Upvotes: 3
Reputation: 595
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...
}
}
Upvotes: 0
Reputation: 215134
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;
Upvotes: 7