Why did we use return here in Recursive Function?

99 Views Asked by At

Why did we use return here in this code in Doubly Linked List Lecture ? When I run the code , the recursion takes place without writing the return kw,Why do we need it then?

Node* reverseusingRecursion(Node* &prev,Node* &curr){
  //*base condition
  if (curr==NULL)
  {
    //*LL has been reversed
    return prev;
  }
   //* 1 case solve rest will be taken care by recursion function(This is the basic escence of a recursive function)
   Node* forward=curr->next;
        curr->next=prev;
        prev=curr;
        curr=forward;

        return reverseusingRecursion(prev,curr);

}

I have written code without using return in * return reverseusingRecursion(prev,curr);* and it works fine. Why do we need to enter return then?

enter image description here

1

There are 1 best solutions below

0
Vlad from Moscow On

The function must return a pointer to the new head node of the reversed list. The pointer to the new head node is obtained in the last recursive call of the function. So all preceding recursive calls of the function must return the pointer obtained and returned in the last recursive call of the function. Without the return statement the returned pointer is undefined.

The function can work as expected accidently if due to the generated object code the function places the pointer prev in a register that is used by the compiler to return a value from the function. But this is not guaranteed.

You always must write a valid C code and do not rely on the generated by a compiler object code..