2

Can I call the main method in C/C++ from other functions. it seems to work but I do not know if it is a good software design in c++. please tell me the pros and cons ? Thank you.

  • 7
    Please choose one of C and C++, the answer might be different. – fuz Nov 21 '15 at 17:48
  • 3
    The answer _is_ different, in fact. – James M Nov 21 '15 at 17:49
  • Why would you ever want to do this? – Destructor Nov 21 '15 at 17:49
  • 1
    main function is usually an entry point for run-time. Depending upon system, the run-time is guaranteed of presence of a particular function that it can call to get the program started. In all cases, only one main function is needed for entry into the application. If you put in good design, then only one such main function is needed by your program – Nandu Nov 21 '15 at 17:51

3 Answers3

10

In C you can. In C++ you can't.

Quoting the C++ standard (§3.6.1.3):

The function main shall not be used within a program.

There's nothing in the C standard forbidding calling main.

Whether or not calling main is good design is quite opinion-based, but usually one would be better off using a loop instead.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
6

According to C++ standard

5.2.2.9 "Recursive calls are permitted, except to the function named main"

Destructor
  • 14,123
  • 11
  • 61
  • 126
1

You've already determined it is possible. However, it makes your entire program recursive. It also could make your code a little harder to understand.

So it's really hard for me to imagine any pros for this.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • I strongly suspect that it by some chance actually works, the results are implementation dependant - as with other classes of undefined behaviour. – marko Nov 21 '15 at 17:59
  • Some programs, like Knights Tour or Eight Queens, can be made simpler by recursing the `main()` function. – Thomas Matthews Nov 21 '15 at 20:07
  • @ThomasMattews I don't know why you wouldn't just create a new recursive function and call that one from `main`. This is not only more standard but allows you to perform any initialization before starting the recursion. – Jonathan Wood Nov 21 '15 at 23:36