Search code examples
cfunction-pointersc89

Cast a long to a function pointer?


I have the following code:

long fp = ...
void (*ptr)(long, char*, char*) = fp;

The long fp is a correct function pointer, which comes in as a long. I am getting the standard "makes pointer from int without a cast" warning. I want to be able to compile with:

-std=iso9899:1990 -pedantic-errors

which turns that warning into an error. The question is: what is the correct cast? I have tried various guesses, e.g.:

void (*ptr)(long, char*, char*) = (void)(*)(long, char*, char*) fp;

But can't seem to find the right one.


Solution

  • The "correct" cast is:

    void (*ptr)(long, char*, char*) = (void (*)(long, char*, char*))fp;
    

    Obviously, this can be tidied up with a suitable typedef.

    But either way, the result of this is implementation-defined. If you can, avoid this, and maintain the pointer in a pointer type. Next best thing would be to use intptr_t if it's available.