Search code examples
creturn

Does return; do anything in this function?


I'm trying to learn linked list following the instructions given in this tutorial and I can't seem to understand whether if the return; in the if statement at step 4 of the following code does anything...

/* Given a reference (pointer to pointer) to the head 
   of a list and an int, appends a new node at the end */

void append(struct Node** head_ref, int new_data) 
{ 
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
    struct Node *last = *head_ref; /* used in step 5*/

    /* 2. put in the data */
    new_node->data = new_data; 

    /* 3. This new node is going to be the last node, so make next of it as NULL*/
    new_node->next = NULL; 

    /* 4. If the Linked List is empty, then make the new node as head */
    if (*head_ref == NULL) 
    { 
        *head_ref = new_node; 
        return; //<<<this return here
    } 

    /* 5. Else traverse till the last node */
    while (last->next != NULL) 
        last = last->next; 

    /* 6. Change the next of last node */
    last->next = new_node; 
    return;  
}

would the following be equally functional as the above if there was no return;statement like this?

/*4. If the Linked List is empty, then make the new node as head */
if(*head_ref == NULL)
{
    *head_ref = new_node;
}
/*step 5*/
/*step 6*/

Solution

  • It does the same thing it does anywhere else, it exits from the function immediately.

    If you don't return, you'll continue executing the function, but it won't work properly. The next block of code is:

    while (last->next != NULL) 
    

    If that if was true, then last == NULL (because of the initialization last = *head). This code will try to indirect through the null pointer, which is undefined behavior.

    There's no point in executing the rest of the code, which appends the new node after the last node in the list. The list was empty, so there's no last node to append to. You've already inserted it as the first node in the if block.

    BTW, if is not a loop. A loop executes code repeatedly, and they're written using for and while. if is a conditional, it either executes the code once or it doesn't execute it at all.