簡體   English   中英

這個 if 條件 & while 語句中 return 的意義是什么?

[英]What is the Significance of return in this if condition & while statement?

/* 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 關鍵字或者沒有這個我的程序也能正常工作?

return關鍵字對於返回類型為 void 的函數是可選的(因為它們不返回任何內容)。 但是,如果使用 return 語句,它會立即停止函數的程序流程並從函數返回。 在您的示例中,在 if 語句中使用 return 可確保在條件為真時函數不會進一步執行。

但是請注意,如果函數的返回類型不是 void,則需要 return 語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM