cfunctionvariablesrecursionreturn

Recursion - Not Returning Values as Expected


I'm currently writing a program to return all additions to a number subtracted from itself (For example, if 3 were the number, the output should be 6 (3+2+1). Essentially, I'm trying to have the function return the permutation of a number, but with addition, instead of mulitplication. This seemed like a perfect situation for a recursive function (something I struggling to understand). In my function, I would expect that the return value is not relevant (during the while loop) as the information is directly contained in the variables (specifically, static b). Yet, when I change the while loop in my function, to anything other than b, the wrong value gets returned from the function, into main() - it's always 0. What's even more confusing is that when I do a printf of b, right before the return of the (second - outside of while loop) b return value, my function prints the correct value (regardless of the return value above). Why must my function return b in the while loop (first return function) for the function to return the correct value, which is 55 (10+9+8+7+6+5+4+3+2+1+0)?

As the code is below, it works correctly.

#include <stdlib.h>
#include <stdio.h>
    
int sumyears(int a)
{
    static int b=0;
    while(a>0)
    {
        b+=a;
        sumyears(a-1);
        return b;  //Program works correctly when I return b, but not when I return any other value, including a
    }
    printf("%d", b); //Program will always print correct value, but return different values based upon the return value in the while loop
    return b;
}
    
int main()
{
    printf("%d", sumyears(10));
}

Solution

  • seemed like a perfect situation for a recursive function (something I struggling to understand)

    You want to compute the sum of all integers up to n.

    As a recursive function:

    #include <stdlib.h>
    #include <stdio.h>
    
    int sumIntsUpTo(int a) {
      return (a <= 0) ? 0 : (sumIntsUpTo(a - 1) + a);
    }
    int main() {
      printf("%d", sumIntsUpTo(10));
    }
    
    

    There is of course a well known explicit formula for that.

    I don't know where you got the idea of using static inside of recursive functions, but I'd suggest to discard this source (delete the link / burn the book / don't talk to the weird person who suggested that). When you're trying to write down a recursive definition, the absolutely last thing that you want to deal with is some global mutable state accessed by each invocation of this function (unless you're generating names... and a couple of other valid use cases that you shouldn't worry about for now).