What is the purpose of while(*variable) and if(!*variable) in the statements "while" and "if"?

Asked

Viewed 275 times

7

In Code Review there is a implementation of a simply chained list that I am using.

However, in the reply of one of the users, he made some modifications to the list, and had a particular modification that left me with doubts.

The modification the user made was in the procedure add():

void add(struct LinkedList *list, int value) {
    if(list->firstElement == NULL) {
        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        list->firstElement = newElement;
    } else {
        struct Element *lastElement;

        lastElement = list->firstElement;

        while(lastElement->nextElement != NULL) {
            lastElement = lastElement->nextElement;   
        }

        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        lastElement->nextElement = newElement;
    }
}

To:

void add(List* head, int value) {
    while(*head)
        head = &head[0]->next;
    *head = malloc(sizeof **head);
    if(!*head) abort();
    **head = (Node){0, value};
}

And my doubt is in the statement while and if, which are declared as follows as shown below:

while(*head)

and:

if(!*head)

It’s the first time I’ve seen a statement from while and if like this one above, using pointer.


Question

I would like to know what these statements while(*head) and if(!*head) mean and what is the purpose of a statement of this type with pointer in flow control commands?

1 answer

4


In the code in question, List is defined as

typedef node* List;

Soon, head is actually pointer pointer to a knot, and *head, therefore saves a pointer to node. The part of the while could be written explicitly as

while (*head != NULL)
    head = &((*head)->next)

That is, you walk on the list until you reach the end of it (indicated by NULL). Similarly, the if can be written as

if (*head == NULL) abort();

As it comes right after malloc, you are checking if it returned NULL (this check was not done in the original code).

Regarding the purpose, I believe that the advantage of the implementation in the code in question, by means of pointers, aims to avoid writing two versions of add() (one with empty list and the other otherwise)as well as it is not necessary to have the last element point to the new after inserting it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.