3

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer, thank you. Yes, I had to do an explicit cast to void* and the other way round to stop the compiler from complaining.
@TomL. - You had to cast to void*? That's rather odd. That one is an implicit conversion. Or do you mean you had to cast the function pointer? That was risky.
I meant the function pointer, sorry. And yes, that was the reason why I didn't like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.