Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting NULL to long is not ambigious?

Tags:

c++

c++11

I was trying out an example for the usages of NULL vs nullptr. As NULL can be casted into integral types, it should show ambiguity with the below example, but it isn't !!

It shows ambiguous candidate compile error, if it is unsigned long, but not for signed long.

Could anyone care to explain why !!

#include <iostream>
using namespace std;

// NOTE: 
// "long" or "signed long" is not showing ambiguous candidates
// but "unsigned long" does

void func(long st) {
    cout << "overload func\n";
}

void func(int* ptr) {
    cout << "integer pointer overload func\n";
}

int main() {
    func(NULL);
    return 0;
}
like image 553
ppadhy Avatar asked Jun 15 '18 18:06

ppadhy


2 Answers

In C++, NULL is defined as integral type. Your compiler probably defines it as long, since it matches that overload. C++ standard explicitly states (draft N3936, page 444):

Possible definitions [of macro NULL] include 0 and 0L, but not (void*)0.

This restriction is necessary, because e.g. char *p = (void*)0 is valid C but invalid C++, whereas char *p = 0 is valid in both.

like image 181
VLL Avatar answered Oct 18 '22 15:10

VLL


As NULL can be casted into integral types, it should show ambiguity with the below example, but it isn't !!

The problem with NULL, which was one of the motivating reasons for introducing nullptr, is that you really cannot say how it should behave. There are numerous different ways that NULL can be defined, and depending on that choice of definition, you could have different behavior here - it could lead to either of the two functions behind called or being ambiguous. You can't say without knowing how your vendor defines that macro.

The nice thing about nullptr is that it will, without question, call the int* overload.

like image 45
Barry Avatar answered Oct 18 '22 15:10

Barry