Search code examples
c++function-pointersundefined-behavior

Is it undefined behavior to compare function pointers reinterpret_cast to void(*)()?


For example, can I make a std::set<void(*)()> and use reinterpret_cast to put arbitrary function pointers into it? I obviously wouldn’t be able to call them, but if I wanted to remember what functions I’ve seen, would seen.count(reinterpret_cast<void(*)()>(fn)) be defined behavior? For now I’m assuming the functions I care about aren’t overloaded.


Solution

  • This is fine. According to [expr.reinterpret.cast],

    A function pointer can be explicitly converted to a function pointer of a different type.

    It also says that converting a function pointer to a different function pointer type and back will yield the original pointer type.