Why is it bad to call functions recursively?

无人久伴 提交于 2021-01-28 00:08:16

问题


In the class I'm taking my teacher is discouraging the students from calling functions recursively. For example, if I want to call the main function in the following code:

if (x > 5) {
    printf("Your number's too high. Enter a number below 5.");
    main();
}

I'm instead encouraged to use:

int x;
while (x > 5) {
    printf("\nYour number's too high. Enter a number below 5.");
    scanf("%d", &x);
}

While I understand that the while function is a simpler way of going about this particular problem, we're being told to avoid recursion in its entirety, especially with main(). However, I thought this was a fairly important concept used in programming. Why should this sort of thing be avoided, especially when calling main()?


回答1:


Great question.

There are types of problems much easier solved with recursion, but in general wherever possible it is usually more efficient to iterate.

The reason for this, in short, is that every time we go into a new function, we have to save the location where we left off along with all the variables that were there, so that when the inner function terminates we can resume in the parent.

Eventually you'll have to remember every parent function's data, which will be a lot, so you'll exhaust your memory. Also the process of saving the data and creating a new context to execute a new function in takes a small amount of time that adds up when you're doing hundreds of thousands of calls.

You can learn more about the sort of cool things that compilers do to make all the things we take for granted (functions, loops) by reading about computer architecture and assembly language.

For example, check out UC Berkeley's class materials on the subject: http://www-inst.eecs.berkeley.edu/~cs61c/fa15/



来源:https://stackoverflow.com/questions/33511917/why-is-it-bad-to-call-functions-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!