简体   繁体   中英

Question about this recursive program, and how return works

In the function prod() , how does the program ever get past the return 1; , and where is it returning to?

When the program prints "test 1 at the beginning", the value of number is 1, the if statement is true, so it hits the return 1 , and shouldn't it terminate there?

Does return not terminate the function?

I understand how the first 4 lines of output work, but I don't know how the code ever reaches the rest of the output. Any help is appreciated and this is just for practice for a future test.

Code below:

#include <stdio.h>

int prod(int number);

int
main(void)
{
    int x = 4;

    printf("The result of this function call is %d.\n", prod(x));
    return 0;
}

int
prod(int number)
{
    int p;

    printf("test %d at the beginning\n", number);
    if (number == 1)
        return 1;
    p = (number + 1) * prod(number - 1);
    printf("test %d at the end\n", number);
    return p;
}

You call prod(4) from main. Within prod, you get past the first return since the conditional (4 == 1) is not true (therefore the return statement never gets executed). Then you arrive at p = (4 + 1) * prod(3) . prod(3) does something similar: p = (3 + 1) * prod(2) . prod(2) sets p = (2 + 1) * prod(1) . Now in prod(1) , we hit the conditional (1 == 1) and this is flagged as true, so we enter into its code block, which simply is return 1 . In a recursive function such as this, the function that returns, or does not recursively call itself is known as the bottom of the recursive stack (or a leaf in some cases). A return statement loads the context that called (the caller) the currently running function (the callee). In our case, the caller is prod(2) . Thus, prod(2) 's p is set to (2+1) * 1 = 3, where 1 is the value just returned. prod(2) then executes the printf and returns its p (which is 3). This is returned to the function that called prod(2) , or prod(3) . prod(3) 's p then is p = (3 + 1) * 3 (= prod(2) return value) = 12. Thus, prod(3) returns 12 back to prod(4) which is our top level of the recursive stack. prod(4) returns p = (4 + 1) * 12 (= prod(3) return value) = 60. This is returned to main in the context of printf .

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