There is such code:

#include <iostream> using namespace std; int func() { cout << "func" << endl; return 0; } int main() { void * p; p = func; cout << p << endl; cout << func << endl; return 0; } 

In Visual Studio 2010, this code compiles beautifully and in both cases prints some address.

Question 1. Is there an implicit conversion that allows you to convert a function (a pointer to a function?) void * type?

Question 2. Why, when passing a function as an argument to an overloaded operator, did the compiler convert the function (pointer to function?) To void * type again, and not, say, to bool ? After all, there is an implicit conversion that allows you to convert a pointer to the bool type.

  • one
    Non-standard behavior from the category "it was a long time and not true." - AnT
  • one
    @AnT: Well, Visual Studio 2017 without the /Za key is still compiling. Backward compatibility and all that. - VladD

1 answer 1

This code does not compile either gcc or MSVC in the mode with the Microsoft language extensions disabled ( /Za ).

So this should not be compiled. Well, why the wrong MSVC code compiles this way, and not otherwise - the details of their internal implementation, I think. In standard compatibility mode ( /Za ) string

 cout << func << endl; 

causes the conversion to bool and the output of the value 1 .


As far as I understand, according to the standard, there is no permission to convert a pointer to a code into a pointer to data [in particular], because on different platforms these pointers may have different lengths.

A list of all possible conversions is in the standard ; converting a function pointer to a void pointer is simply not mentioned there. The closest thing there is 7.11 / 2 :

A prvalue of type “pointer to cv T ”, where it is an object type, can be converted to a prvalue of type “pointer to cv void ”. The pointer value is unchanged by this conversion.

This rule allows you to convert a pointer to an object into a pointer to a void , but not a pointer to a function.

  • It is worth noting that explicit conversion is conditionally supported: Converting a conditional support. If you want to make it a little bit different, it’s possible to use it. - Croessmah
  • @Croessmah: Well this is via reinterpret_cast only (and even then conditionally). - VladD