Hi I am studying basic Linked List right now. I am reading a related book and got stuck in this line.
1 2 3
if(!head)
head = newNode;
"head" is pointer that was declared as a private member variable of another class called "NumberList" and will be initialized to nullptr by its constructor.
My question is what does pointer variable with "!" operator mean ?
In the book, it says "Because 'head' is a null pointer, the condition '!head' is true." How does this if statement work?
nullptr is basically an alias for 0, except it's "pointer-like". So if (head == nullptr)
is equivalent to if (head == 0)
In fact, 0 was the preferred value to use for null pointers before nullptr came around.
Now, checking equality to zero is the same as comparing to false, so if (head == 0)
is equivalent to if (head == false)
Finally, logically x == false is the same predicate as !x. (!x) == (x == false), no matter the value of x. So if (head == false)
is equivalent to if (!head)