Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Q_A Avatar asked Nov 28 '22 01:11

Q_A


2 Answers

No, the C++ standard disallows calling main manually.

To cite the standard (C++11: 3.6.1 Main Function)

The function main shall not be used within a program. The linkage (3.5) of main is implementation-defined. A program that defines main as deleted or that declares main to be inline, static, or constexpr is ill- formed. The name main is not otherwise reserved.

like image 148
Leandros Avatar answered Dec 09 '22 16:12

Leandros


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);
}
like image 36
πάντα ῥεῖ Avatar answered Dec 09 '22 15:12

πάντα ῥεῖ