Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

G++ Compiler won't allow recursion?

Tags:

c++

recursion

I have created a very simple program that uses recursion. I'm using the g++ compiler. I can compile it, but when I try to run it I get an error message that says SEGMENTATION FAULT. Here's my code:

#include <iostream.h>
using namespace std;

int Recurse(int);

int main(int argc, char *argv[])
{
        Recurse(10);
        cout << endl;
}

int Recurse(int numTimes)
{
    if (numTimes == 0)
        return 0;
    else
        {
                cout << numTimes << " ";
        Recurse(numTimes--);
        }
}
like image 328
Kredns Avatar asked Nov 27 '22 22:11

Kredns


1 Answers

In your recursive call, you're using the postfix -- (numTimes--), rather than the prefix version (--numTimes). As a result, the value of numTimes is decremented after the recursive call. This means that Recurse is called with 10 infinitely. Use the prefix version (which will decrement it before the call), or just pass numTimes-1 (since the numTimes value doesn't need to be modified).

The reason you're seeing a segfault is that your stack overflows into protected memory.

like image 144
Jesse Rusak Avatar answered Nov 29 '22 13:11

Jesse Rusak