Tom L.
Tom L.

Reputation: 1002

Function pointer with struct parameter inside struct

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.

Upvotes: 3

Views: 82

Answers (1)

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.

Upvotes: 4

Related Questions