无法理解此 return 语句的功能,没有它就会发生运行时错误

Not able to understand the function of this return statement, without it a runtime error occurs

本文关键字:运行时错误 功能 return 语句      更新时间:2023-10-16

在下面bstcreate()函数的if语句中,如果我删除return语句,则会发生运行时错误。 为什么?

即使没有return语句,进程也不应该转到while语句,因为所有语句都会被执行吗?

下面是代码:

struct Node{
struct Node *lchild;
int data;
struct Node *rchild;
}*root=NULL;
void bstcreate(int key)
{
struct Node*t=root;
struct Node*p,*r=NULL;
if(root == NULL)
{
p = (struct Node*)malloc(sizeof(struct Node));
p->data = key;
p->lchild = p->rchild = NULL;
root = p;
return;
}
while(t)
{
r=t;
if(key<t->data)
{
t=t->lchild;
}
else
{
t=t->rchild;
}
}
p = (struct Node*)malloc(sizeof(struct Node));
p->data = key;
p->lchild = p->rchild = NULL;
if(r->data>key)
{
r->lchild=p;
}
else
{
r->rchild=p;
}
}

如果列表为空,bstcreate()root设置为新Node,然后由于没有其他事情可做,因此应立即退出。return语句执行该退出。 由于该函数被声明为返回void,因此不需要提供return的值。

t

初始化为rootr初始化为NULL。 如果删除return语句,并且在进入时rootNULL,则最初tNULL导致跳过while循环,然后在访问r的成员时发生崩溃,因为r仍然NULL,因为循环未将r分配给指向任何位置。