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?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With