In Week 7's Wednesday lecture, Prof. Malan went over the program list-0.c. I don't get why the while loop in search() can execute.

The node* ptr was first set to point at whatever the node* first is pointing to before executing the loop. Then the loop executes while (ptr != NULL). But at the top of this program the node* first was declared as a global variable and intialized to NULL. So wouldn't this cause ptr to be NULL and the while loop not to execute altogether?


Absolutely correct. If search() is the first operation called then the first node variable will be NULL and the loop will not execute.

However, if you inspect the code for insert(), you may see that a value is assigned to the first node. For example, from line 123:

// initialize node
printf("Number to insert: ");
newptr->n = GetInt();
newptr->next = NULL;

// check for empty list
if (first == NULL)
    first = newptr;

Here we see that if first is NULL, then a node is assigned to it, and from then on first will contain a value.

This is an excellent question because it highlights one of the reasons why global variables are considered bad practice - because it is hard to know exactly what code is changing them.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .