[Solved] Why does int main() { return main(); } cause stackoverflow and not tail recursion?


The code you have shown will call main infinitely, and therefore will result a stack overflow. This is true in the case of any function and not specific to main. Each function call a stack frame is created in memory, and as infinite such frames is created as the recursion goes deep, you get a stackoverflow.

But if you make a proper base termination like the example as follows, for recursive calls in main then there is an interesting thing.

int main (void)
{
  static int x = 100;

  if (x == 0)
  {
    return 0;
  }
  x--;
  printf ("%d\n", x);
  main ();
  return 0;
}

There is a difference in calling main recursively in C and C++ Language, and I think it is interesting to point that out. Here is a post I wrote, I am giving some explanation about it.

C++ Standards talk about these in

Section 3.6.1 Paragraph 3

Recursive calls are permitted, except to the function named main. 

and Section 5.2.2 Paragraph 9

The function main shall not be used within the program. … … … 

I did not find any such restriction in the C standards. What I found about recursive calls in the C99 standards in Section 6.5.2.2 Paragraph 11 is as follows

Recursive function calls shall be permitted, both directly and indirectly through any chain of other functions. 

Therefore calling main recursively in C Language is deterministic. But as per C++ standards calling main from any function or recursively is not allowed.

solved Why does int main() { return main(); } cause stackoverflow and not tail recursion?