首页 > 解决方案 > 这个 if 条件和 while 语句中 return 的意义是什么?

问题描述

/* 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;
    } 

    /* 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;
} 

上面 if & while 条件中的 return 关键字有什么用?

是否有必要给这个 return 关键字或者没有这个我的程序也可以正常工作?

标签: calgorithm

解决方案


对于返回类型为 void 的函数,该return关键字是可选的(因为它们不返回任何内容)。但是,如果使用 return 语句,它会立即停止函数的程序流程并从函数中返回。在您的示例中,在 if 语句中使用 return 可确保如果条件为真,该函数将不会进一步执行。

但是,请注意,如果函数的返回类型不是 void,则需要 return 语句。


推荐阅读