Is it legal for a C++ reference to be NULL?
- by BCS
A while back I ran into a bug the looked something like this:
void fn(int &i)
{
printf(&i == NULL ? "NULL\n" : "!NULL\n");
}
int main()
{
int i;
int *ip = NULL;
fn(i); // prints !NULL
fn(*ip); // prints NULL
return 0;
}
More recently, I ran into this comment about C++ references:
[References arguments make] it clear, unlike with pointers, that NULL is not a possible value.
But, as show above, NULL is a possible value. So where is the error? In the language spec? (Unlikely.) Is the compiler in error for allowing that? Is that coding guide in error (or a little ambiguous)? Or am I just wandering into the minefield known as undefined behavior?