Tuesday, September 23, 2008

Usage of C++ NULL vs 0

There's a very common confusion between C++ developer as which one we should use for pointer assignment, NULL or 0???

 

NULL is a macro and defined to 0. But for readibility purpose one should use NULL for poiner and 0 for integer. 

Also since system provide NULL to be defined to some value(today it is 0) and if tomorrow the defined value changes, then still the code will be portable if NULL is used. So I think instead of using hard coaded value 0, we 
should use NULL for pointer. It increases both for readbility and portability.

 

But many C++ developers prefer 0 because it avoids the need to #include whichever header NULL was defined in. 

  The only situation where using 0 as null pointer might cause ambiguity problems is in overloading situations like this: 

void foo(int i); 
void foo(SomeType*); 

int main() 

    foo(0); // ambiguous 

  In practice the int version of the function will be called (although I'm not 100% sure what the standard says about this), which might not be what the programmer wanted. 

  A properly-implemented NULL would avoid the ambiguity. Rather oddly, though, the NULL macro in many compilers still cause ambiguity, and a "foo(NULL);" will call the int version regardless (gcc at least issues a 
warning, though). 

Moreover, there may be some confusion about what the latest standard says, but it at least used to be true that in C NULL was ((void *)0)  At least on some systems.  This is illegal in C++. 

 

 

0 comments: