c - 这个 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 关键字或者没有这个我的程序也可以正常工作?
解决方案
对于返回类型为 void 的函数,该return
关键字是可选的(因为它们不返回任何内容)。但是,如果使用 return 语句,它会立即停止函数的程序流程并从函数中返回。在您的示例中,在 if 语句中使用 return 可确保如果条件为真,该函数将不会进一步执行。
但是,请注意,如果函数的返回类型不是 void,则需要 return 语句。
推荐阅读
- angular - 将其传递给组件时的空数组(输入)
- wpf - WPF - DataTrigger 的问题,它只工作一次
- javascript - 我在模式窗口小部件中的条件控件不允许编辑现有条件,但允许创建和保存新条件
- postgresql - Postgres 政策的范围是什么?
- r - Blogdown Hugo Academic 总是产生相对链接
- flutter - 在调用后传递授权标头
- kubectl - 如何使用 kubectl 获取多个服务的状态?
- c++ - 构造函数中的错误处理而不会失败
- kotlin - 从辅助构造函数调用 SuperConstructor
- node.js - npm install 在我的角度项目中不起作用