Tuesday, 23 March 2010

0 vs NULL in C++

Just thought I'd drop a line.

Consider this snippet:
1 #include <stddef.h> // NULL macro
2 void foo(int);
3 void foo(void*);
4 int main()
5 {
6     foo(0);
7     foo(NULL);
8 }
Compiling it gives an error on line 7:
[max@truth test]$ g++ -Wall -o test test.cc
test.cc: In function ‘int main()’:
test.cc:7: error: call of overloaded ‘foo(NULL)’ is ambiguous
test.cc:2: note: candidates are: void foo(int)
test.cc:3: note:                 void foo(void*)
Why is the error? Is NULL different from 0 in C++? Let's check it out:
[max@truth test]$ g++ -E -dD -Wall test.cc | grep NULL
#undef NULL
#define NULL __null
#undef __need_NULL
So, NULL is defined as a gcc keyword __null. The difference between __null and integer constant 0 is that 0 converts to int more easily than to a pointer, hence foo(0) calls foo(int). Whereas __null is not an integer constant and converts to int and a pointer equally easy, so that the compiler can not figure the best overload of foo() from a set of viable functions foo(int) and void(void*).

Using NULL can be helpful in C++ with function overloading, when 0 can silently convert to int where conversion to a pointer is expected.

No comments:

Post a Comment