Home > Enterprise >  Why do I need to avoid "casting a function pointer to a generic pointer" in this case?
Why do I need to avoid "casting a function pointer to a generic pointer" in this case?

Time:11-13

assume that I have a struct that has a function pointer as a member:

struct Class
{
    void (*function)();
}

I then want to assign a function to this member. I wanted to do this:

typedef void (*func_pointer)();
func_pointer method = va_arg(arg_list, func_pointer);
struct Class foo;

since the type of both foo.function and method are void (*)() (a "generic" function pointer) I assume that I can just equate them together, something like foo.function = method.

However, the book I'm reading mentioned that casting between "void *" and a "function pointer" is illegal. Therefore they did something like this:

*(func_ptr*) &foo.function = method;

Why though? why is it necessary? I do not see any void * pointer here. Why can't I just copy the value of method to foo.function?

CodePudding user response:

I would not hide any pointers behind typedefs (even function pointers). It makes code difficult to read and error-prone.

typedef void func();

struct Class
{
    func *fptr;
};

struct Class bar(int x, ...)
{
    va_list va;
    func *fp;
    struct Class c;

    va_start(va, x);
    fp = va_arg(va, func *);
    c.fptr = fp;

    return c;
}

You do not need any casts.

CodePudding user response:

There's no problem with your code, and there's also no problem with that passage in the book. The "problem" is that the passage doesn't apply to your code.

the book I'm reading mentioned that casting between "void *" and a "function pointer" is illegal.

This is true. See this question/answer.

But in your code you don't have a void*. foo.function is a void(*)() (a pointer to a function taking any number of arguments and returning void), which is the same type as func_pointer. So there's no need to do any sort of casting. foo.function = method; is correct.

  • Related