Search code examples
c++recursionprogram-entry-point

Recursion in the main function


I tried recursion in the main function, but why 'i' variable is not getting updated, it only gets updated till i=1 and then remains constant. Below is the code:-

int main(int i = 0)
{
    std::cout << "i value" << i << std::endl;
    if (i == 3)
        return 0;
    std::cout << "hello" << std::endl;
    main(i++);
}

Solution

  • See for example cppreference/main_function:

    The main function has several special properties:

    1. It cannot be used anywhere in the program

      a) in particular, it cannot be called recursively

      b) its address cannot be taken

    [...]

    You cannot call main recursively. Also your signature is not correct. Correct signatures are:

    int main () { body }                                                (1)     
    int main (int argc, char *argv[]) { body }                          (2)     
    /* another implementation-defined form, with int as return type */  (3)
    

    For (3) you need to check your implementation, I am not aware of one that allows int main(int) (though I didn't bother to check).

    Last but not least, foo(i++); will increment i and then call foo with the original value of i. You probably want foo(++i); or rather foo(i + 1);.

    TL;DR

    int my_main(int i=0) {
         // put code here
         my_main(i + 1);
    }
    
    int main() {
       my_main();
    }