Hacker News new | ask | show | jobs
by mpyne 4913 days ago
It's actually a different answer for C or C++ programmers.

NULL should be defined as ((void * )0) for C always (and you should define your own NULL to enforce that if necessary in varargs functions). This is safe because C allows conversion from void * to other pointer types.

C++ does not allow conversion from void * to other pointer types, so what you were supposed to do was use plain 0, which introduced exactly the issue you mention (and which has bitten me before trying to use a C library from C++, where NULL was defined as plain 0).

With C++11 you should use nullptr, which does the right thing. Some implementations define NULL in C++ to a vendor-provided symbol which emulates nullptr so it might be safe to use NULL. If you have C++98 only and don't want to risk NULL then you should use static_cast<T*>(0) (where T is the actual pointer type), which is admittedly clunky.

1 comments

No! C and C++ are define NULL identically: it can be either 0 or (void * ) 0 at the discretion of the compiler author.

So the bug you mention which bit you by using "C library from C++" was not caused by a difference between C and C++. It was caused by a difference in the definition of NULL between those two compilers. You could just as easily have found a C++ compiler which did work, or a C compiler which didn't.

If you think a C++ compiler has the option to define NULL as ((void * ) 0) then all I ask is that you simply try it yourself and let me know what compiler error you get. Make sure to turn off permissive flags.

    class Foo { };
    int main() {
        Foo *foo = malloc(sizeof(Foo)); // returns void*
    }
You are confusing the preprocessor #define named NULL with the null pointer. Your code example involves void pointers, which is yet a third thing.
That's because NULL is the pre-processor define. The null pointer itself has no name in C or C++ (pre-11), except that the language will convert integer '0' into whatever the hardware's null pointer is (usually also 0) when converting integral types to pointer types. C++11 added a name and specific type for the null pointer but that's about it.