I have a struct which currently looks like this (abbreviated to show only the essential parts):
typedef struct {
uint32_t baudrate;
... some other internally used values here
void (*request_received)(void* hbus); //< this is what I'm talking about
} hbus_options_t;
This works. Basically it contains a function pointer which takes a pointer to a parameter of type void.
What I would actually like is for this to be easier to understand:
typedef struct {
uint32_t baudrate;
... some other internally used values here
void (*request_received)(hbus_options_t* hbus); //< this doesn't work
} hbus_options_t;
Obviously the compiler needs to know the struct before I can use it. How is this done usually? Using a void pointer works but it's harder to understand.
It's done by not being remiss and providing a struct tag:
typedef struct hbus_options {
uint32_t baudrate;
... some other internally used values here
void (*request_received)(struct hbus_options * hbus);
} hbus_options_t;
Besides readability, the compiler will also complain if you pass a pointer to something other than the intended struct type.
Adding a tag also allows for looser coupling of components. One can forward declare a structure, but not a type alias.
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.