Akankshi Mishra
Akankshi Mishra

Reputation: 65

How to call main() from other functions in C

I was going through the difference in C and C++ and I found a tricky point. Can you please elaborate the below points:

  1. In C, we can call main() Function through other Functions.
  2. In C++, we cannot call main() Function through other functions.

How to call main() from another function and what is the use case of it?

Upvotes: 0

Views: 10332

Answers (1)

Myst
Myst

Reputation: 19221

@TrevorHickey hit the nail on the head (where did his answer go?) - C++ forbids calling main from within a different function (for good reason)... Not that any compiler is likely to stop you (I don't think most of them care).

An obvious workaround would be to move main's functionality into a container function and call it from there, as suggested by @KlasLindbäck.

i.e.

int my_application(int argc, char const * argv[]) {
   // do stuff
   return 0;
}

int main(int argc, char const * argv[]) {
   return my_application(argc, argv);
}

Another "hack" that probably only works because compilers let you call main anyway (As also pointed out by @KlasLindbäck in the comments), would be to use function pointers. i.e.

int main(int argc, char const * argv[]) {
   // do stuff
}

// shouldn't compile... but hey, you never know.
int (*prt_to_main)(int, char const* argv[]) = main;

void test_run(void) {
   prt_to_main(0, NULL);
}

Upvotes: 1

Related Questions