Kredns
Kredns

Reputation: 37211

G++ Compiler won't allow 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--);
        }
}

Upvotes: 4

Views: 655

Answers (4)

Steve Willard
Steve Willard

Reputation: 16737

Firstly, you want to use

#include <iostream>

Without the .h

Now for the program:

#include <iostream>
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 << " ";
        return Recurse(--numTimes);
    }
}

You need to apply the - 1 before evaluation.

Upvotes: 3

Arnold Spence
Arnold Spence

Reputation: 22282

You are incrementing numTimes after you pass it to Recurse() so you are blowing the stack by continuously recursing into Recurse with the value 10 and never outputting anything to cout.

Upvotes: 3

Jesse Rusak
Jesse Rusak

Reputation: 57178

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.

Upvotes: 33

Andy White
Andy White

Reputation: 88385

It might be the "numTimes--" that is causing the infinite recursion. The postfix -- will decrement the value within the -- method, but will return the original value of the variable.

Try changing it to --numTimes.

Upvotes: 5

Related Questions