Conclusion of C ++ recursion for no apparent reason

I wrote a function using recursion. It turned out that during testing, the function is disabled for no obvious reason, while recursion still works.

To test this, I wrote endless recursion.

On my PC, this function ends in about 2 seconds, and the last exit is about 327400. The last number is not always the same.

I use Ubuntu Lucid Lynx, the GCC compiler and Eclipse as an IDE. If anyone has an idea what the problem is and how I can prevent the program from exiting, I would be very happy.

#include <iostream>

void rek(double x){
    std::cout << x << std::endl;
    rek(x + 1);
}

int main(int argc, char **argv) {
    rek(1);
}
+5
source share
8 answers

, , . , , , , .

+5

, , , ,

, gcc ?

, gcc . , -O3 gcc .: -)

O2 O3.

+3

( ), .

void rek(double x){
   if(x > 10)
      return;
   std::cout << x << std::endl;
   rek(x + 1);
}
+2

, ?

. - .

+1

, stackoverflow.com.;) ( ), - , , , .

+1

, , , - , , , . , , (.. Lisp, , Haskell ..) . , . C - (: gcc x86, int double, . C ++, . , "\n\t" , gcc):

#include <stdio.h>

void rek(int x)
{
    printf("Value for x: %d\n", x);

    //we now duplicate the equvalent of `rek(x+1);` with tail-call optimization

    __asm("movl 8(%ebp), %eax\n\t"   //get the value of x off the stack
          "incl %eax\n\t"            //add 1 to the value of x
          "movl 4(%ebp), %ecx\n\t"   //save the return address on the stack
          "movl (%ebp), %edx\n\t"    //save the caller activation record base pointer
          "addl $12, %ebp\n\t"       //erase the activation record
          "movl %ebp, %esp\n\t"      //reset the stack pointer
          "pushl %eax\n\t"           //push the new value of x on the stack for function call
          "pushl %ecx\n\t"           //push the return value back to the caller (i.e., main()) on the stack
          "movl %edx, %ebp\n\t"      //restore the old value of the caller stack base pointer
          "jmp rek\n\t");            //jump to the start of rek()
}

int main()
{
    rek(1);
    printf("Finished call\n");  //<== we never get here

    return 0;
}

gcc 4.4.3 Ubuntu 10.04, "" , , , . __asm , "", . ( ) , .

, , , . , / Lisp/ .. , , .

+1

, , . ; .

int main(...)
{
   double x = 1;
   while (true)
   {
       std:cout << x << std::endl;
       x += 1;
   }
 }
0

, , .

In your case, there is no condition for the parameter that you pass to the function, therefore, it works forever and ultimately fails.

0
source

All Articles