Search code examples
crecursionglobal-variables

How do I get a result from a recursive function without using a global variable?


I wrote a function that reverses an integer (123 becomes 321) with recursion, and I was told that using global variables is bad practice, but I'm having trouble figuring out how to get the result from the function without using one. I tried declaring the variable inside the function, but then I get undesired results.

#include <stdio.h>

int result = 0;

int reverse_num(int num)
{
    int remainder = num % 10;
    
    if (num == 0) return 0;
    
    result *= 10;
    result += remainder;
    
    reverse_num(num / 10);
    
    return result;
}

int main(void)
{
    int num, reversed_num;
    
    printf("Insert number: ");
    scanf("%d", &num);
    
    reversed_num = reverse_num(num);
    
    printf("Inverted number: %d", reversed_num);
    
    return 0;
}

Solution

  • The common way to do this is to have another argument just for the accumulated result. It can be accomplished in C by splitting your function into the one called by the user and the one that does all the work.

    int reverse_num_helper(int num, int result)
    {
        int remainder = num % 10;
        
        if (num == 0) return result;
        
        result *= 10;
        result += remainder;
        
        return reverse_num_helper(num / 10, result);
    }
    
    int reverse_num(int num)
    {
        return reverse_num_helper(num, 0);
    }
    

    (In C++ you could combine the two into int reverse_num(int num, int result = 0).)

    Notice how your function is essentially unchanged.
    We made only two minor modifications:

    • returning result instead of zero when num reaches zero
    • invoking recursion with the modified result value