Search code examples
cpass-by-reference

I'm having a hard time using pass by reference


I don't know why I keep on getting errors in my code when I'm trying to do pass-by-reference, for finding the largest number of an integer using recursion.

My code works when it's pass-by-value, but I fail to do it correctly in pass-by-reference.


My main:

#include <stdio.h>
#include <math.h>

void largest_digit(int* digit);

int main() {
   int num;

   printf("\nPlease enter a number ");
   scanf("%d", &num);

   largest_digit(&num);
   printf("The largest digit = %d\n", num);

   return 0;
}

My function:

void largest_digit(int* digit) {
   int hold, hold1;

    if(*digit == 0 || *digit < 0) {
        *digit = 0;
        *digit;
        return;
    }

    // If-statement with Recursion.
    if(*digit > 0){
        hold = *digit % 10;
        hold1 = largest_digit(*digit/10);

        if(hold > hold1) {
            hold = *digit;
            *digit;
            return;
        } else {
            hold1 = *digit;
            *digit;
            return;
        }
    }
}

Solution

  • As someone said before, the largest_digit function is void, so it can't be assinged to a variable when is called. What you can do instead, is modifying *digit before the call, and then assign the value of *digit to what you want, in this case hold1.

    Other thing is that you need to save the value into *digit before returning, for example, instead of doing hold = *digit, you should do *digit = hold.

    Here are the suggested modifications:

    void largest_digit(int* digit) {
       int hold, hold1;
    
        if(*digit == 0 || *digit < 0) {
            *digit = 0;
            return;
        }
    
        // If-statement with Recursion.
        if(*digit > 0){
            hold = (*digit) % 10;
            (*digit) /= 10;
            largest_digit(digit);
            hold1 = *digit;
    
            if(hold > hold1) {
                *digit = hold;
                return;
            } else {
                *digit = hold1;
                return;
            }
        }
    }
    

    With this main,

    int main() {
    
       int a=123, b=652, c=3274;
       largest_digit(&a);
       largest_digit(&b);
       largest_digit(&c);
       printf("%d\n",a);
       printf("%d\n",b);
       printf("%d\n",c);
    
       return 0;
    }
    

    the output is

    3
    6
    7