Hey guys, I was using a switch statement for a menu so when the user entered a number from the menu that action was taken. The last option in the menu when pressed just said thanks for using the program then it would say press any key to continue.

Although for some reason this wouldn't be displayed after another option was chosen from the menu (it would just display some information from the last menu option the user had entered) so I had to use the exit(0) function.

I was just wondering why the first method didn't work?

Thanks in advance.

Dani AI

Generated

Quick diagnosis and a simple pattern to avoid the trap mentioned by (and what hinted at): the behaviour is almost always a control-flow issue. If the menu lives inside a function and the "quit" case only uses break, execution returns to the caller and any code there will run next — so the "thanks" message can be missed or immediately overwritten. Calling exit(0) forces termination, but it is heavyweight and skips normal structured returns or local cleanup (and in C++ it prevents local automatic destructors from running).

A clean, portable approach is to have the menu handler return a status and let main() own the loop. This keeps control flow explicit and easy to maintain:

#include <stdio.h>
#include <stdbool.h>

bool show_menu(void) {
    int opt;
    printf("1) Do thing\n2) Quit\n> ");
    if (scanf("%d", &opt) != 1) return true;
    switch (opt) {
    case 1:
        printf("Doing thing...\n");
        break;
    case 2:
        printf("Thanks for using the program\n");
        return false; /* tell caller to stop */
    default:
        printf("Invalid option\n");
    }
    return true; /* continue */
}

int main(void) {
    while (show_menu()) { /* repeat until show_menu() returns false */ }
    return 0;
}

Additional tips: avoid fflush(stdin) (undefined behavior), flush output with fflush(stdout) when waiting for user input, and prefer fgets()/sscanf() over raw scanf() to avoid leftover newline issues. If the menu is deep in nested calls, propagate an explicit return code (or a global/flag) rather than calling exit() or using longjmp — that keeps cleanup predictable and makes debugging simpler.

Recommended Answers

All 2 Replies

Well we're not psychics. Let me just look thru the provided source and we'll see your problem.

Hi, thanks for your reply.. sorry it was very silly of me not to post the source code, although I have figured out the problem it seems to be because I was calling the menu from another function so when I selected exit from the switch statement as I hadn't used the exit() command it went back to the previous function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.