Casts between pointer-to-function and pointer-to-object in C and C++

c, c++

Solution

- In C++03, such conversions were illegal (not UB). The compiler was supposed to issue a diagnostic. A lot of compilers on Unix systems didn't issue a diagnostic. This was essentially a clash between standards, POSIX vs C++.

- In C++11, such conversions are "conditionally supported". No diagnostic is required if the system does supports such conversions; there's nothing to diagnose.

- In C, such conversions officially are undefined behavior, so no diagnostic is required. If the system happens to do the "right" thing, well that's one way to implement UB.

- In C99, this is once again UB. However, the standard also lists such conversions as one of the "common extensions" to the language:

J.5.7 Function pointer casts A pointer to an object or to void may be cast to a pointer to a function, allowing data to be invoked as a function (6.5.4). A pointer to a function may be cast to a pointer to an object or to void, allowing a function to be inspected or modified (for example, by a debugger) (6.5.4).

Problem

Am i wrong about the following? C++ standards says that conversion between pointer-to-function and pointer-to-object (and back) is conditionnaly-supported with implementation-defined semantics, while all C standards says that this is illegal in all cases, right? ``` void foo() {} int main(void) { void (*fp)() = foo; void* ptr = (void*)fp; return 0; } ``` ISO/IEC 14882:2011 5.2.10 Reinterpret cast [expr.reinterpret.cast] 8 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. I can't find anything about it in C standard right now...

Original source