3

I'm in my first semester at university studying C programming. We've gained an introduction to modularising our code, and the basic gist of my problem is that I've created a function which prompts the user to continue or exit the program. Obviously I have a few other functions before this and I call these in main(). Bear in mind the functions are in separate C files. I wish to loop back to main() if the user inputs 'Y' (i.e. to start the program from the beginning), but given my beginner knowledge I've had a hard time figuring out how to go about this. Any help/guidance would be appreciated!

int continueOrExit() {
    char response; 
    char upperResponse;
    printf("Do you wish to continue the program? Y/N");
    scanf("%c", &response);
    upperResponse = toupper(response);

    while(upperResponse == 'Y')
        main(); // this is the bit which I struggle with

    .....
    }

2 Answers2

5

You should not run your main() again from inside a function already called from main(). Well, you could; recursive calls are possible, but you definitely don't want to do it in this case.

What you want to do is for your continueOrExit() to return true when user chooses to continue, and put a selected large part of your main() body in a loop:

do
{
    /* your code here */
} while (continueOrExit());
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Boris Lipschitz
  • 1,514
  • 8
  • 12
2

Going from one function directly to another is against the rules of structured programming. It may be used for handling of errors (longjmp), but such a mechanism should be used sparingly - only when you really have an error which you cannot handle in any other way.

To implement the "start over" functionality, you have to structure your code with that in mind. For example:

int exitByUserRequest()
{
    char upperResponse;
     ...
    return (upperResponse != 'Y');
}

int main()
{
    do
    {
        ...
    } while (!exitByUserRequest());
}

Here, the main function calls exitByUserRequest and interprets its exit code.

If you have several layers of functions between main and "ask user whether to continue", all of them should pass the information "exit or continue" to the caller, using return codes. Therefore, you should avoid this situation - your "exit or continue" should be called directly from main.

anatolyg
  • 26,506
  • 9
  • 60
  • 134