A deep understanding of recursive functions, many people's misunderstanding

Source: Internet
Author: User

a long time to send notes, this time sky (my nickname) for everyone to explain a thing, speak of the great God do not spray ha

#include <iostream>
using namespace std;
void Bin (const unsigned int &i)
{
    
if (I/2)
bin (I/2);
cout << i%2;
}

int main ()
{
int A;
cin >> A;
bin (a);
cout << Endl;
return 0;
}
This is a binary program that asks for a number,
for such recursive function everyone is certainly not unfamiliar, but believe that many people still do not know its implementation process, or mistakenly think that they think is right, the following I will answer for everyone:
How does a recursive function end? 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.
program execution is like this, if the number passed in is 6, then the first if () is judged to be true, then the execution Bin (I/2), after execution will also execute cout << i%2; But this sentence just put it into the stack, not on the screen output, This is the first recursive function recursion, the second entry will be the second cout << i%2, into the stack, and so on, until the judgment of if () is false, then the recursion will end, at this point, the stack is advanced, so is the first output of the final execution cout << i%2;
Many people think that the first execution of the bin () will not execute cout << i%2; This understanding is wrong, because recursion is to call the function itself repeatedly, the call function is a process of the stack, If you don't understand it, you can disassemble the program and see what the compiler is doing.

A deep understanding of recursive functions, many people's misunderstanding

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.