what does the function returns with in C program , in case if there is no return statement in the code

后端 未结 3 1207
情书的邮戳
情书的邮戳 2021-01-24 04:40

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

the function is as below.

struct node * reverseSLL2(struct node *p,struct node         


        
相关标签:
3条回答
  • 2021-01-24 04:45

    When a non-void function returns without a return statement, it is Undefined Behaviour (UB). Make sure to avoid this.

    However, the function still might return something even without using the return statement. For example, on x86 architectures, the function will return whatever is there in the eax register, which will most probably be one of the local variables.

    0 讨论(0)
  • 2021-01-24 04:49

    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.

    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.

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

    return reverseSLL2(temp1,p);
    
    0 讨论(0)
  • 2021-01-24 04:56

    I'll bet you're running on a machine where the function result is in a register (EAX on 32-bit x86 for example), and the return value from the recursive call is still sitting in that register when you return without a value by falling off the end of the function. The compiler doesn't have to use that sequence, so it's still Undefined Behavior.

    You can fix your version by simply adding the return to the recursive call:

    return reverseSLL2(temp1,p);
    
    0 讨论(0)
提交回复
热议问题