Hello,

I'm trying to understand linked list but i'm having problems with the way my text describes one aspect.

This is the problem i'm having:

The text says:
//If there are no nodes in the list make newNode the first node
and then test it like this:

head =NULL;

if (!head)
head = newNode;

The problem i'm having is this seems to be saying if head is NOT = null then execute, but the text says this statement SHOULD be executed which implies that it is NULL.

The text is from starting out with c++ tony gaddis (Linked List)

Any help is appreciated.
Art

Ok, so the statement you are having an issue with is:

if(!head)

Lets go by it step by step. First, the if-statement, of course, takes a boolean value (true or false) and executes the next statement if that boolean value is true.

Then, the ! operator is the NOT boolean operator (logic operator) it simply takes a "false" and turns it into a "true", and vice versa.

Finally, the head is a pointer, but the NOT operator is for a boolean value. So, C/C++ provides a implicit conversion from pointer to bool. This conversion returns a "true" value for any pointer that is not NULL, and "false" if the pointer is NULL.

So the statement if(!head) will do this:
For a NULL pointer head:
- the head pointer will be converted to the boolean value "false".
- the boolean value "false" will be flipped by the ! or NOT to become "true".
- the if statement will recognize the "true" value and execute the following line.
For a non-NULL pointer head:
- the head pointer will convert to a "true" value.
- the "true" value is switched to a "false" value.
- the if-statement will not execute the following line (and execute the "else" case if one exists).

So, conclusion, this statement does exactly what the author describes.

Thanks Mike,

I know you're right. I've stepped thru code to see what it does, but I don't get the !head, isn't this the same as saying not null, since head is initialized to null in the beginning? The problem for me is it seems to be saying if this is not null then execute, but it is null so why does it execute. I'm looking at your reply again to see if it will dawn on me what's going on.

Thanks again,
Art

GOT IT!!!

Thanks Mike went over your logic again and I NOW see what you're saying!!!

How do I give you points for this answer or label it closed?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.