简体   繁体   中英

Calling recursive function inside a loop

I'm getting two problem when I call the recursive function inside a loop. Consider the following sample code:

int fact(int x)
{
    if(x == 1)
        return 1;
    return x*fact(x-1);
}

int main() { 
    int n = 2;
    for(int i = 0; i < n; i++);
        std::cout << fact(4) << std::endl; // 24 ??
    return 0;
}

Problem 1: My expected result for this program is 24 24 (two times 24 to be printer) but the actual result I got only one 24 .

Problem 2: What is the reason for the main() function called repetitively even I'm not recursively calling the main function.

It'd be great if anyone give me your thoughts about how to call the recursive function inside the loop for getting multiple output.

for(int i=0; i < n; i++); <---------------------- notice this
       std::cout << fact(4) << std::endl; // 24 ??

Notice the ; after the for loop. That is the reason why you get only one output. The std::cout is executed after the loop exits; it is outside the loop.

That is the answer to your first question. Now the second question:

What is the reason for the main() function called repetitively even I'm not recursively called the main function.

I don't think the code which you've posted has this problem. You must be doing something else in the code which you've not posted, because of which main() is getting called recursively.

Note that calling main() from your code (recursively or otherwise) is forbidden by C++ language specification. So if you compile it with -pedantic option with GCC, then it shouldn't compile if you, by chance, call main() from your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM