Recursive call -- C ++ primer plus

Source: Internet
Author: User

#include <iostream>void countdown(int n);int main(){countdown(4);return 0;}void countdown(int n){using namespace std;cout<<"Counting down ... "<<n<<endl;if(n>0){countdown(n-1);}cout<<n<<": Kaboom!\n";}

Note that each recursive call creates its own set of variables. Therefore, when the program reaches 5th calls, there will be five independent n variables, each of which has different values. To verify this, you can modify the program list to display the address and value of N:

void countdown(int n){using namespace std;cout<<"Counting down ... "<<n<<" n at "<<&n<<")"<<endl;if(n>0){countdown(n-1);}cout<<n<<": Kaboom!"<<"         (n at "<<&n<<")"<<endl;}

Counting down ... 4 n at 0012FF30)Counting down ... 3 n at 0012FED8)Counting down ... 2 n at 0012FE80)Counting down ... 1 n at 0012FE28)Counting down ... 0 n at 0012FDD0)0: Kaboom!         (n at 0012FDD0)1: Kaboom!         (n at 0012FE28)2: Kaboom!         (n at 0012FE80)3: Kaboom!         (n at 0012FED8)4: Kaboom!         (n at 0012FF30)

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.