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
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)
andf(char*)
, the callf(0)
unambiguously resolves tof(int)
. There is no way to write a call tof(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:
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.