can void* be used to store function pointers? [duplicate]

Maybe. Until C++11, they couldn’t; but C++11 adds:

Converting a function pointer to an object pointer type or vice versa is
conditionally-supported. The meaning of such a conversion is
implementation-defined, except that if an implementation supports
conversions in both directions, converting a prvalue of one type to the
other type and back, possibly with different cvqualification, shall
yield the original pointer value.

This doesn’t appear to have made it into C yet.

The reason why you can’t convert between them, of course, is because
they may not have the same size or format. Posix requires that they do
have the same size and format, and I would expect all Posix compilers to
support the conversion; most did before anyway, even though it made them
non-conformant.

EDIT:

A little more information. After rereading the C standard, I think
conversions between object pointers and function pointers are undefined
behavior: the C standard doesn’t seem to require a diagnostic in this
case, but it definitely doesn’t define any behavior for it. As
undefined behavior, an implementation (or Posix) is free to define it.
Or just do anything it wants, without documenting it.

On the otherhand, C++, pre C++11, required a diagnostic (although
a number of compilers didn’t give one). In C++11, as per the paragraph
quoted above, it is implementation defined whether an implementation
supports it or not, and if an implementation supports it, they are
required to document its behavior. So in all cases, an implementation
is required to document what it does, and if it does not support it, it
is required to issue a diagnostic if the code tries to do the
conversion.

Leave a Comment