Search code examples
c++castingnullc++03nullptr

Finding a Pointer to NULL


I have int* foo[SIZE] and I want to search it for the first element that points to NULL.

But when I do this:

 std::find(foo, foo + SIZE, NULL)

I get the error:

error C2446: '==' : no conversion from 'const int' to 'int *'

Should I just be using static_cast<int*>(NULL) instead of NULL?

C++11 solves this via nullptr but that's not an option for me in C++03


Solution

  • This problem is actually called out in Herb Sutter and Bjarne Stroustrup's: A name for the null pointer: nullptr:

    Distinguishing between null and zero. The null pointer and an integer 0 cannot be distinguished well for overload resolution. For example, given two overloaded functions f(int) and f(char*), the call f(0) unambiguously resolves to f(int). There is no way to write a call to f(char*) with a null pointer value without writing an explicit cast (i.e., f((char*)0)) or using a named variable

    So we see that this problem can be solved by either:

    1. An explicit cast
    2. The declaration of a value with matching type, for example: const int* piNULL = NULL

    Ideally when using the explicit cast a C-Style cast can be avoided. Either of these C++-Style casts effectively returns an int* containing address NULL:

    • reinterpret_cast<int*>(NULL)
    • static_cast<int*>(NULL)

    http://en.cppreference.com/w/cpp/types/NULL asserts that:

    A null pointer constant may be implicitly converted to any pointer type; such conversion results in the null pointer value of that type

    And since static_cast:

    Converts between types using a combination of implicit and user-defined conversions

    static_cast more closely defines the type of cast intended than does reinterpret_cast which:

    Converts between types by reinterpreting the underlying bit pattern

    So, in C++03 static_cast<int*>(NULL) is the tightest inline definition of C++11's nullptr that can be achieved.