Search code examples
c++recursioninfinite-loop

Why is this recursive function creating an infinite loop?


The following code results in an infinite loop. The value of a does not seem to be going lower than 1. Please help.

int main()
{
    init(4);
    return 0;
}
void init(int a)
{
    int j;      
    cout<<"After declaring: "<<j;
    j = a;
    cout<<"After initializing: "<<j;
    a--;
    while(a>0)
    {   
        init(a);    
    }   
}

Solution

  • First, you are accessing an uninitialized variable. This introduces undefined behaviour into your program; I'd remove this section.

    Second, your while-loop runs as long as a > 0, but in the body of the loop, the value of a is never changed. Note that when calling init, parameter a is passed by value, i.e. the value of a is copied; Each instance of init will get it's own a, and it will never change the value of the caller's a.

    Recursive functions usually are used instead of a loop. Nevertheless, you need an "anchor" to tell the recursion where to stop:

    void init(int a)
    {
        int j = a;
        cout<<"After initializing: " << j;
        if (a>0) {
           init (a-1);
        }  
    }