void* ptr = &func; compiles with msvc without any diagnostic but both gcc and clang rejects it

227 Views Asked by At

I am learning C++ using the book "C++ Primer" by Stanley. In particular, the section about "pointer conversions" says:

a pointer to any nonconst type can be converted to void*


After reading this I wrote the following program that compiles with msvc without any diagnostic but is rejected by both gcc and clang. Demo

int func()
{
    return 4;
}
int main()
{
    void* ptr = &func; //works with msvc but rejected by clang and gcc
}

As you can see the above program works with msvc but gcc says error: invalid conversion from 'int (*)()' to 'void*'.

I want to know which compiler is correct here. Note that I've used /permissive- flag with msvc to make it standard conformant.

1

There are 1 best solutions below

0
On

The program is ill-formed because there is no implicit conversion from a pointer to a "function type" to void*. The implicit conversion is only allowed if the target is an "object type" which int() is not. This can be seen from conv.ptr#2 which states:

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

Further from dcl.init#general:

Otherwise, the initial value of the object being initialized is the (possibly converted) value of the initializer expression. A standard conversion sequence ([conv]) is used to convert the initializer expression to a prvalue of the cv-unqualified version of the destination type; no user-defined conversions are considered. If the conversion cannot be done, the initialization is ill-formed. When initializing a bit-field with a value that it cannot represent, the resulting value of the bit-field is implementation-defined.

(emphasis mine)

Note the emphasis on the word "object type". And since in your code T=int() is a "function type" there is no conversion from int(*)() to void* meaning the program is ill-formed and msvc is wrong in accepting the program without any diagnostic.