0

I read in C you can recursively call main, but why would you do it?

GMB
  • 19
  • 1

2 Answers2

0

There isn't a good reason to do it, and it is almost always a bad idea. It just isn't forbidden.

Everything that can be done by calling main recursively can also be done some other, less obscure way, for example by defining a well-named function that is called immediately after entering main and calling that function recursively.

It is allowed in C because it was not explicitly forbidden - as main is just a function, that would require an explicit rule. On the contrary, some additional support for it has been added in the standard over the years, as discussed in answers to this related question. Adding such a rule forbidding it now would be a breaking change and is therefore hardly feasible in practice, and arguably also a waste of effort, as this is rarely a problem.

Hulk
  • 6,399
  • 1
  • 30
  • 52
0

At first glance, I wouldn't say it is a "bad" idea. It's more like a weird idea. main is just a normal function like everything else. For example, a program that prints the arguments given in reverse:

#include <stdio.h>
int main( int argc, char *argv[] ) {
   if( argc <= 1 ) return 0;
   printf( "%s\n", argv[argc - 1] );
   return main( argc - 1, argv );
}

That being said, more recent C++ standards state that calling main is forbidden. This isn't C++, but that should still be held relevant.

Why should it be forbidden? There could be a number of reasons, despite common compiler implementations not caring about that rule and it working anyway. What speculation comes to mind for me is that that main can actually be implemented as a special entry point, some kind of jump in the assembly that will mangle your stack if you try and call it again. Basically, not a good idea, at least for future-proof code.

While examples for this behavior may be pretty much limited to small academic curiosities, I would pose a certain maintenance issue as the primary reason to avoid it:

  • It isn't recommended,
  • it is forbidden in a closely related standard, and
  • that means it might not work in the future.
mukunda
  • 2,908
  • 15
  • 21
  • 2
    For C++, I think that in some implementations, the compiler may add code to `main` to call global constructors, so that it doesn't need help from the system startup code to make sure they execute. If `main` can be called recursively then it needs to make sure that the constructors aren't executed on the subsequent calls. This is probably as simple as setting a flag, but if recursive calls to `main` are totally forbidden, then the compiler's job becomes a little easier. – Nate Eldredge May 05 '20 at 16:38
  • I think that's a good example too, @NateEldredge. More constraints = easier implementation. – mukunda May 05 '20 at 18:27