递归函数:自己调用自己
    必须设置正确的停止条件,否则程序会非常危险。

    1. #include <iostream>
    2. using namespace std;
    3. void div2(double val);
    4. int main()
    5. {
    6. div2(1024.); // call the recursive function
    7. return 0;
    8. }
    9. void div2(double val)
    10. {
    11. cout << "Entering val = " << val << endl;
    12. if (val > 1.0)
    13. div2(val / 2); // function calls itself
    14. else
    15. cout << "--------------------------" << endl;
    16. cout << "Leaving val = " << val << endl;
    17. }

    如果将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