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.
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" whichint()
is not. This can be seen from conv.ptr#2 which states:Further from dcl.init#general:
(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 fromint(*)()
tovoid*
meaning the program is ill-formed and msvc is wrong in accepting the program without any diagnostic.