Deep understanding of recursive functions, many misunderstandings, and deep understanding of Recursion

Source: Internet
Author: User

Deep understanding of recursive functions, many misunderstandings, and deep understanding of Recursion

I haven't been able to take notes for a long time. This time, sky (my nickname) will explain something to everyone. What's wrong with me?

# Include <iostream>
Using namespace std;
Void bin (const unsigned int & I)
{

If (I/2)
Bin (I/2 );
Cout <I % 2;
}

Int main ()
{
Int;
Cin>;
Bin ();
Cout <endl;
Return 0;
}
This is a binary program for finding a number,
There are certainly no strangers to such recursive functions, but I believe many people still do not know the execution process, or mistakenly think they are right. I will answer the following questions:
How does a recursive function end? It is the sign of the end of the recursive function. In this program, the sign of the end of the recursive function is that if (I/2) is false,
The recursive function ends.
If the input number is 6, the first time if () is true, bin (I/2) is executed ), after execution, cout <I % 2 is executed. However, this sentence only writes it into the stack and does not output it on the screen. This is the first time that the recursive function performs recursion, during the second entry, the cout <I % 2; of the second entry is added to the stack, and so on until the if () is determined to be false. Then, recursion ends, at this point, the stack starts to output, and the stack is first and later. Therefore, the final cout output is <I % 2;
Many people think that if bin () is executed for the first time, cout <I % 2; is not executed. This is wrong because recursion is to call the function repeatedly, calling a function is a process of going into the stack. If you really don't understand it, You can disassemble the program and check the execution process of the compiler.

Related Article

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.