Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a recursive function call need to return a value to calling function?

In the following recursive function,

int subtractByOne(int num) {
    printf("%d\n", num);
    if (num == 0)
        return 0;
    return subtractByOne(num - 1);
}

Why is the final return necessary? From what I understand, the base case will always stop the recursion and when control reaches the end of the function (after the recursive call) the function will transfer control to whomever called it without the return.

My knowledge of stack frames and return addresses is weak, but the stack should receive a return address independent of the actual return keyword, no?

Visual Studio 2015 throws a warning about control paths, which I understand. However, during a programming course a grader's IDE would not compile similar code and the professor commented the code was incorrect as opposed to just bad practice. I fixed the code at the time, but never understood why it was incorrect.

like image 352
Uriah Wardlaw Avatar asked Sep 04 '26 08:09

Uriah Wardlaw


1 Answers

The function definition says it will return an integer. If you do not put the last return the only the base case will return the value 0 and transfer the control to the previous (caller) function but no other return will be occur.

You probably do not need the return value in this case, and so you may use void as return in the function definition, and get rid of all the return altogether, however in many case you will need the return. One such simple example is to calculate the sum of 1...n integers as follows:

int sum(int n)
{
   if(n==0)
       return 0;
   return n + sum(n-1);
}
like image 75
Md Monjur Ul Hasan Avatar answered Sep 07 '26 00:09

Md Monjur Ul Hasan