2
votes

I have read that "Checking if a reference equals null is meaningless in C++" - because references can never have a null value. But, I see that this statement does not hold in the following example I came up with:

void InsertNode(struct node*& head, int data)
{
    cout << head << endl;

    node* temp = new node();
    temp->data = data;
    temp->next = NULL;

    if (head == NULL)
        head = temp;
    else
    {
        temp->next = head;
        head = temp;
    }
}

I am checking if (head == NULL). Even though, head is passed as a reference, I am checking if it equals NULL. This contradicts with the statement that I read "Checking if a reference equals null is meaningless in C++" - Could any one please explain if my understanding is right ? Thanks.

1
No need for struct in the parameter list in C++. Separate namespaces for structures and other types only exist in C. - Ulrich Eckhardt
You are not checking the reference. You are checking the referent, which happens to be a pointer. - n. 1.8e9-where's-my-share m.
Testing the reference would be if (nullptr == &head). - Jarod42
@n.m A reference is an alias to 'something' and this 'something' is called the referent right ? then this means, checking the reference and checking the referent is same right - given reference is just an alias to the referent. - prasha6
@Jarod42 Doesn't "&head" return the address of the head ? - prasha6

1 Answers

7
votes

You don't check if the reference is null but whether it refers to a null pointer, which is something different.

Maybe an example would help:

int i = 42;
// check if a variable is null
if (i == 0) print("i is null");

// pointer
int* pi = &i;
// check if a pointer is null
if (pi == 0) print("pi is null");
// check if a pointer points to a null
if (*pi == 0) print("i is null");

// reference
int& ri = i;
// check if a reference refers to a null
if (ri == 0) print("i is null");

There is another description of a reference that might help: A reference is a self-dereferencing, non-null pointer. That means that you never have to write *pi to get at the object it points to, but just ri. It also means that it is guaranteed to be non-null. Note that you can write programs that break this guarantee, but those programs cause so-called undefined behaviour anyway, so it's not worth bothering with it and hence the statement that initially confused you.