如果代码中没有return语句,函数在C程序中返回什么 [英] what does the function returns with in C program , in case if there is no return statement in the code

查看:13
本文介绍了如果代码中没有return语句,函数在C程序中返回什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个函数,说明如何在 C 中递归地反转单链表.

I made a function on how to reverse a singly linked list recursively in C.

功能如下.

struct node * reverseSLL2(struct node *p,struct node *temp)
{
    struct node *temp1;
    if(p!=NULL)
    {
        temp1=p->link;
        p->link=temp;
        reverseSLL2(temp1,p);
        //return;
    }
    else
    {
        return temp;
    }    



}

我调用 head=reverseSLL2(head,NULL) ,其中 head 是指向我的链表第一个节点的指针.程序正常运行!

I call head=reverseSLL2(head,NULL) , where head is the pointer to the first node of my linked list.The program works correctly!

但是,我有两个问题:

1)我对函数的所有调用,除了最后一次调用,都没有到达return语句,那么这些函数用什么返回?

1) My all the call to the function except the last call , do not reach to the return statement , then what does those functions returns with ?

2) 如果我写(取消注释)之前代码中已注释的返回语句.在这种情况下,函数返回什么?

2) If I write(uncomment) the return statement that has been commented in the previous code. In that case what does the function returns with ?

谢谢.

推荐答案

这是未定义的行为.编译代码应该会产生一个警告,提示您通过缺少 return 的代码路径到达函数末尾.

This is undefined behavior. Compiling the code should produce a warning about reaching the end of a function through a code path that is missing a return.

您没有看到函数损坏并观察它产生正确结果的原因是因为从基本案例分支(即 else)返回的实际值确实有一个正确的return.编译后的代码可能会在堆栈上的所有函数调用中重用最后一个返回值,因此调用者最终会得到预期的值.

The reason you do not see that the function is broken, and observe it producing the right results, is because the actual value that is returned from the base case branch (i.e. the else) does have a correct return. It is possible that the compiled code reuses that last return value in all invocations of the function up the stack, so the caller ends up getting the intended value.

但是,代码无效.您应该在递归调用前面添加 return 来解决问题:

However, the code is invalid. You should add return in front of the recursive call to fix the problem:

return reverseSLL2(temp1,p);

这篇关于如果代码中没有return语句,函数在C程序中返回什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆