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.