0

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?

6
  • Possible duplicate of Call main() itself in c++? Commented Jul 25, 2016 at 6:32
  • 4
    You can, but it isn't good practice. If you ever feel like you'd want to, then create another function with the same signature and call it instead. Commented Jul 25, 2016 at 6:41
  • how? just write main() or main(argc, argv). There's no difference from other functions Commented Jul 25, 2016 at 6:42
  • 3
    There is no real world use case for calling main from another function AFAIK. Commented Jul 25, 2016 at 6:57
  • The use cases, IMHO, are: 1. a very bad way to run a loop while bombarding the stack in an attempt to bring a machine to it's knees... 2. terrible recursive argument parsing... There's a reason C++ thought it should protect itself from people who can't write a while loop... Commented Jul 25, 2016 at 7:08

1 Answer 1

1

@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); } 
Sign up to request clarification or add additional context in comments.

3 Comments

I think any compiler that is lenient enough to allow to take the address of main into a function pointer would also be lenient enough to allow you to call it directly. GCC is one such example.
@KlitosKyriacou, I totally agree. I don't think most of them do more then issue a warning anyway... not that I've tried (I can see no good coming from calling main in any way).
You cannot call my_application() with no arguments.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.