递归函数:自己调用自己
必须设置正确的停止条件,否则程序会非常危险。
#include <iostream>
using namespace std;
void div2(double val);
int main()
{
div2(1024.); // call the recursive function
return 0;
}
void div2(double val)
{
cout << "Entering val = " << val << endl;
if (val > 1.0)
div2(val / 2); // function calls itself
else
cout << "--------------------------" << endl;
cout << "Leaving val = " << val << endl;
}
如果将16行代码的判断条件设置成if(val > -1.0)
,val
是浮点数除法,一直被处以2,足够小的时候,就会被近似为0,0/2会一直为0,造成无穷递归。又因为每次函数调用,都会有栈操作,消费栈内存,无穷递归会一直消耗栈内存,直到内存溢出。
- Pros.
- Good at tree traversal,树操作用栈很方便
- Less lines of source code
- Cons.
- Consume more stack memory
- May be slow.
- Difficult to implement and debug