Search code examples
c++program-entry-point

C++ - Restarting a game by calling the main() function


I'm building a small game. One of the input options is to restart the game. The only way I could think of doing this was to call the main function from within the main function

int main(int argc, char argv[]) {
 ...
 if (input == "restart") {
  main(argc, argv);
 }

Is this bad form? Will it even work?


Solution

  • You can't call main() recursively. That's actually undefined behavior.

    Use a loop instead:

    int main() {
         bool restart = false;
         do {
             // Do stuff ...
    
             // Set restart according some condition inside of the loop
             if(condition == true) {
                 restart = true;
             } // (or simplyfied restart = condtion;)
         } while(restart);
    }