简体   繁体   中英

How does recursive function return its value?

I'm trying to understand "Recursion" topic and i cant get how this recursive function return its argument after it leaves "if" provision.

int sum(int x);
int main(){
    int num;
    printf("Enter a num : ");
    scanf("%d",&num);
    int result=sum(num);
    printf("Result : %d\n",result);
    return 0;
}
sum(int x){
    if (x > 4){
        return sum(x-1);
    }
}

For example, if i edit my "sum" function as "if (x>2)" it will return 2 value. Thats what im wondering. Sum(2) doesnt have any value but it returns 2. Thanks!

 sum(int x){ if (x > 4){ return sum(x-1); } } 

does not return a value because a return is missing in the else branch and only that missing else branch finishes the recursion

i cant get how this recursive function return its argument after it leaves "if" provision.

Because of the missing return the behavior is undefined , if I do on my computer :

pi@raspberrypi:/tmp $ ./a.out
Enter a num : 2
Result : 2
pi@raspberrypi:/tmp $ ./a.out
Enter a num : 12
Result : 4
pi@raspberrypi:/tmp $ ./a.out
Enter a num : 44
Result : 4

but the result can be anything else

Your code does not compile as listed...and not returning from your sum function is causing undefined behavior. But more to your question, your recursion needs to eventually "bottom out". There needs to be some scenario in which a "base case" is met and the function returns something other than itself. For example, try running the below code and see how x changes with different input...

#include <stdio.h>

int sum(int x);
int main() {
    int num;
    printf("Enter a num : ");
    scanf_s("%d", &num);
    int result = sum(num);
    printf("Result : %d\n", result);
    return 0;
}

int sum(int x) {
    if (x > 4) {
        printf("x is %d\n", x);
        return sum(x - 1);
    }
    return 10;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM