If return is used in recursion, the return function will not go away. Isn't it necessary?

Source: Internet
Author: User
If return is used in recursion, the return function will not go away. Isn't it necessary? If return is used in recursion, the return function will not go away. Isn't it necessary?

Reply content:

If return is used in recursion, the return function will not go away. Isn't it necessary?

Http://jsfiddle.net/cj6tY/

Return is the end of the current function. For the parent function that calls it, you have completed the execution of this function, and the parent function will then execute the next statement.
I didn't expect the parent function to immediately encounter another return. The parent function is over. For the grandfather function, the execution of the parent function is complete, and the grandfather function then executes the next statement.
Unexpectedly...
Unexpectedly...

Return to the place where the recursive function is initially called.

Four basic principles of recursion: (from data structure and algorithm analysis-C language description by Mark Allen Weiss)
1. baseline.
2. Continuous promotion.
3. Design Rules.
4. synthetic benefit rules.
Here we use the example functions in the previous answer to Song XiaoBei to explain the first two questions that are very relevant to the subject.

The reference condition of this function is num <= 1. In this case, it can be solved without recursion, that is, 1 is returned directly. I think this is what the subject said: "return will not go, no need to return ".
Return numFact (num-1); is "continuous advancement ". Return 8Fact (8-1); you need to know fact (7). To know fact (7), you need to return 7.Fact (7-1); To know fact (6), you need to return 6Fact (6-1 );.... This continues until a "benchmark situation" occurs ". In the above hwz's answer, the parent function is a metaphor of the grandfather function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.