Soulimane Mammar
Soulimane Mammar

Reputation: 1858

Why do compilers behave differently when static_cast(ing) a function to void*?

The following code compiles without any error in VSC++2017 and doesn't compile in gcc 7.3.0 (error: invalid static_cast from type ‘int(int)’ to type ‘void*’ void* p = static_cast<void*>(func))

#include <iostream>

int func(int x) { return 2 * x; }

int main() {

    void* p = static_cast<void*>(func);
    return 0;
}

Upvotes: 9

Views: 451

Answers (1)

eerorika
eerorika

Reputation: 238351

Functions are implicitly convertible only to function pointers. A function pointer is not a pointer in the strict meaning of the word in the language, which refers only to pointers to objects.

Function pointers cannot be converted to void* using static_cast. The shown program is ill-formed. If a compiler does not warn, then it fails to conform to the standard. Failing to compile an ill-formed program does not violate the standard.


On systems where void* is guaranteed to be able to point to a function (such as POSIX), you can use reinterpret_cast instead:

void* p = reinterpret_cast<void*>(func);

But this is not portable to systems that lack the guarantee. (I know of no system that has a C++ compiler and does not have this guarantee, but that does not mean such system does not exist).

Standard quote:

[expr.reinterpret.cast]

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 cv-qualification, shall yield the original pointer value.

Note that this conditional support does not extend to pointers to member functions. Pointers to member functions are not function pointers.

Upvotes: 8

Related Questions