I am writing a console application that considers a series of decomposition functions. There is a requirement that the application ask the user to "Try again? Y / n" and restart when entering y .

I implement it like this:

  wchar_t tryAgain; do { puts("\n Wanna try again? (y/n)"); fflush(stdin); } while(scanf("%c", &tryAgain) !=1); switch(tryAgain) { case 'y': system(argv[0]); break; case 'n': system("exit"); break; default: system("exit"); } 

But the problem arises: in this way a new copy of the program is created in memory:

That's what happens

This is not quite rational, and therefore the question arises: is it possible to restart the application instead of creating a new instance in memory?

  • Yes, of course, you can. Check out man execv (there is still some kind of analog in Windows) - avp
  • It is not clear for what purpose the application should be terminated, and why not implement a loop inside the application? - dsnk

3 answers 3

Wrap the main code in a loop. If there is no answer, exit the loop and, as a result, end the application. If the answer is yes, the cycle simply repeats, as a result, the execution constantly occurs in one process. The main thing to remember to initialize the values ​​of variables.

     wchar_t tryAgain; while(1) { //your code here puts("\n Wanna try again? (y/n)"); fflush(stdin); scanf("%c", &tryAgain); if(tryAgain=='n' || tryAgain=='N') { break; } } 

      I would advise you to use goto in this case, but using them is a bad programming style. Therefore it is better to use cycles. Here is an example similar to your question:

       wchar_t tryAgain; for(;;){ for(;;){ //Ваш код тут printf("\n Wanna try again? (y/n)"); fflush(stdin); scanf("%c", &tryAgain); if(tryAgain=='n' || tryAgain=='N') break; } } 

      An experienced programmer always knows how to replace goto in his program.