3

Please consider the following code:

int f(int i){return i*i;};

int main() {

    void* p = static_cast<void*>(&f);

    return 0;
}

As you can see here the code does not compile. Why is static_cast from int (*)(int) to void* not allowed in C++?

BlueTune
  • 1,023
  • 6
  • 18
  • https://stackoverflow.com/questions/36645660/why-cant-i-cast-a-function-pointer-to-void – Mat Mar 12 '20 at 21:53
  • 2
    Does this answer your question? [Why can't I cast a function pointer to (void \*)?](https://stackoverflow.com/questions/36645660/why-cant-i-cast-a-function-pointer-to-void) – Tarek Dakhran Mar 12 '20 at 21:53
  • 1
    reopened - the "duplicate" was a different language (as well as not really addressing the question) – M.M Mar 12 '20 at 21:57
  • @M.M The answers look fairly decent, and C vs C++ is not likely to be a factor on this topic. Can always add a new answer on the dupe if you think better can be done :) – Asteroids With Wings Mar 12 '20 at 22:06
  • Maybe start [here](https://stackoverflow.com/questions/5579835/c-function-pointer-casting-to-void-pointer?noredirect=1&lq=1#comment27514415_16682718) – Asteroids With Wings Mar 12 '20 at 22:07
  • @AsteroidsWithWings C and C++ are different languages ; the equivalent cast is not supported in ISO C, whereas it is conditionally supported in ISO C++ – M.M Mar 12 '20 at 22:37
  • @M.M Thank you, I'm well aware that they're different languages, but the underlying reasons for both rules are inevitably related to real-world practicalities which go far beyond the technicality of which programming language you're using. I'm not necessarily saying we should have one Q&A for both languages but re-opening because "was a different language" in this case seems excessive – Asteroids With Wings Mar 12 '20 at 22:45
  • @AsteroidsWithWings the other Q/A made no mention of being conditionally-supported in C++ so it does not correctly answer this question. At best it is background information – M.M Mar 12 '20 at 22:57

1 Answers1

5

You cannot cast a function pointer to void* with static_cast, but you may be able to do so with reinterpret_cast.

This is conditionally-supported with implementation-defined semantics, except that casting back to the original function pointer type yields the same pointer value, so that it may be used again to call the function.

Probably you aren't allowed to do anything else with the void* obtained in such a way, but you will need to look at the compiler documentation to determine that. (Compilers should document implementation-defined behavior, but it often isn't done well or at all.)

Especially on POSIX systems and Windows this cast is always supported.

walnut
  • 21,629
  • 4
  • 23
  • 59