Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does overload resolution select pointer type for 0 but not 1, when it could select ellipses in either case?

I have the following snippet of code:

void eval(void*) { std::cout << "hello world\n"; }
void eval(...) { }
int main(int argc, char *argv[])
{
    std::cout << "0: "; eval(0);
    std::cout << "1: "; eval(1);
    return 0;
}

which gives the output:

0: hello world
1: 

My question is: Why does overload resolution select the void* version of eval instead of the ... version for 0, but not for 1? It seems like in both cases it could infer that the argument is an int and take the variadic version.

like image 843
stett Avatar asked Mar 04 '20 17:03

stett


1 Answers

Because of backwards compatibility, 0 is convertible to a pointer. It was used as the NULL pointer. Nowadays nullptr is used, but 0 still needs to be convertible, otherwise old code would not compile anymore.

If you compile with the highest warning level enabled in your compiler, chances are the compiler will warn you whenever 0 is used as a pointer.

like image 90
Nikos C. Avatar answered Sep 28 '22 07:09

Nikos C.