Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Menu Driven Programs in C
Learn how a switch inside an infinite loop becomes the heart of every console tool, bootloader shell and embedded firmware in this free C tutorial for embedded systems.
A menu driven program in C shows the user a list of choices, reads one choice, performs the matching action and then shows the list again. Every serial console on a router, every bootloader prompt and every factory-test tool on an embedded board follows this pattern. In this lecture of our free C programming course you will combine two control statements you already know, switch and an infinite loop, into a clean menu skeleton that you can reuse for embedded C programming projects.
In This Lecture
What You Will Learn
- How a
for(;;)orwhile(1)loop keeps a menu alive until the user quits. - How
switchselects exactly one action per choice, and why every case needsbreak. - How to validate input with the return value of
scanfso a stray letter never hangs your program. - The difference between leaving a menu with
return,exit()andbreak. - How the same structure maps to a super-loop on a microcontroller.
Prerequisites
You should be comfortable with printf, scanf, the switch statement (covered in the previous lectures) and the for and while loops. Any C compiler works; the examples were built with GCC using gcc -Wall -Wextra -std=c11, which is the same toolchain you will later use for cross compiling.
Anatomy of a Menu Driven Program in C
Strip away the details and every menu driven program has the same five steps. The loop is infinite on purpose: the program has no idea how many times the user wants to act, so it keeps going until a special choice, usually called Quit or Exit, ends the run.
Think of the loop as the waiter and the switch as the kitchen. The loop keeps asking “what would you like?”, while the switch looks at the answer and sends it to the right place. Nothing else in the program needs to know how many dishes exist.
| Part | C construct | Job |
|---|---|---|
| Repeat forever | for(;;) or while(1) | Keeps the menu on screen after every action |
| Show options | printf | Tells the user what is allowed |
| Read choice | scanf("%d", &choice) | Stores the selection in an int |
| Dispatch | switch / case / break | Runs exactly one block of code |
| Leave | return or exit() | Ends the program from the Quit case |
| Catch mistakes | default: | Handles numbers that match no case |
Building an LED Console Menu in C
Instead of printing dummy messages, let us simulate something real: a console that controls a single LED on a board. We keep one variable, led_on, as the “hardware state” and a counter for how many times the user toggled it. On real hardware the assignments would become register writes or a GPIO driver call, but the control flow stays identical.
The Complete Program
#include <stdio.h>
int main(void)
{
int choice;
int led_on = 0;
int toggles = 0;
for (;;)
{
printf("\n--- LED Console ---\n");
printf("1. LED ON\n");
printf("2. LED OFF\n");
printf("3. Toggle LED\n");
printf("4. Show status\n");
printf("5. Quit\n");
printf("Choice: ");
if (scanf("%d", &choice) != 1)
{
printf("Not a number, stopping.\n");
return 1;
}
switch (choice)
{
case 1:
led_on = 1;
printf("LED is now ON\n");
break;
case 2:
led_on = 0;
printf("LED is now OFF\n");
break;
case 3:
led_on = !led_on;
toggles++;
printf("LED toggled -> %s\n", led_on ? "ON" : "OFF");
break;
case 4:
printf("State: %s, toggles so far: %d\n",
led_on ? "ON" : "OFF", toggles);
break;
case 5:
printf("Bye!\n");
return 0;
default:
printf("Invalid choice %d, try 1-5\n", choice);
}
}
}
How to Build and Run
gcc -Wall -Wextra -std=c11 -o led_menu led_menu.c
./led_menu
Typing the choices 1, 4, 3, 3, 4, 9 and 5 (one per prompt) produces the following. Each time the menu text is printed again; only the response lines are shown here to keep the output short.
Choice: LED is now ON
Choice: State: ON, toggles so far: 0
Choice: LED toggled -> OFF
Choice: LED toggled -> ON
Choice: State: ON, toggles so far: 2
Choice: Invalid choice 9, try 1-5
Choice: Bye!
Walking Through the Logic
- State lives outside the loop.
led_onandtogglesare declared beforefor(;;). If you declared them inside, they would reset to zero on every pass and the console would forget everything. - Input is checked.
scanfreturns the number of items it successfully read. Anything other than 1 means the user typed something that is not a number, so we stop instead of looping forever on bad input. - Toggle uses logical NOT.
!led_onflips 0 to 1 and 1 to 0, which is the cleanest way to invert a flag in C. - The ternary operator picks the label.
led_on ? "ON" : "OFF"avoids a second if-else just for printing. - default catches the rest. Any number outside 1 to 5 reaches
default, so the user always gets feedback.
Embedded connection
On a microcontroller there is no operating system to return to, so firmware is usually one giant infinite loop, often called the super-loop. A UART command shell inside that loop has exactly the structure you just wrote. The only change is that the Quit case disappears, because firmware never “exits”.
Choosing Between exit, return and break
Beginners often wonder how to leave the menu. There are three tools and they behave differently when a switch sits inside a loop.
| Statement | What it leaves | Use it when |
|---|---|---|
break inside switch | Only the switch, never the loop | Finishing a normal case |
return in main | The whole program | Quitting cleanly from main |
exit(code) | The whole program, from any function | Quitting from a helper function |
flag + while(running) | The loop, then runs cleanup code | You must free resources or save state before ending |
This is the classic trap: writing break in the Quit case and expecting the program to end. It only leaves the switch, the loop spins again and the menu reappears. If you want a loop-controlled exit, use a flag:
int running = 1;
while (running)
{
/* print menu and read choice */
switch (choice)
{
case 5:
running = 0; /* loop condition fails on next check */
break;
/* other cases */
}
}
printf("Cleaning up...\n");
The flag version is better whenever something must happen after the loop, such as closing a file or switching an LED off before the program ends.
Common Mistakes and Troubleshooting
break execution falls through into the next case. If case 1 lacked its break, choosing 1 would also run case 2 and print both messages. Compile with -Wextra; GCC then warns about unintended fall-through.
| Symptom | Likely cause | Fix |
|---|---|---|
| Menu repeats forever after Quit | break used instead of return | Use return 0 or a running flag |
| Endless output when a letter is typed | scanf result ignored, bad character stays in the buffer | Check scanf(...) != 1 |
| State resets each time | Variables declared inside the loop | Declare them before the loop |
| Two actions run for one choice | Missing break | End every case with break or return |
| Wrong case runs for 1 vs ‘1’ | Mixing int and char input | Pair %d with case 1:, or %c with case '1':, never mix them |
Best Practices for Embedded C Menus
- Always include a
defaultbranch, even when you think every value is covered. - Keep each case short. If an action needs more than a few lines, move it into a function and call it from the case.
- Use named constants (
#define CMD_QUIT 5) instead of bare numbers once the menu grows. - Never trust input. Validate the return value of
scanf, and check ranges before using the number as an array index. - Performance: a dense switch with consecutive case values is usually compiled into a jump table, so dispatch time does not grow with the number of cases.
- Security: menus that accept strings instead of numbers must limit the length they read, otherwise a long line overflows the buffer. That topic returns when we study arrays and strings.
Real-World Uses of Menu Driven Programs
- Serial debug consoles on development boards, where typing a number runs a test.
- Factory test tools that exercise LEDs, buttons and sensors one at a time.
- ATM and kiosk style terminal software.
- Bootloader prompts that let you pick a boot source.
Summary and Key Takeaways
- A menu driven program is an infinite loop wrapped around a switch.
breakleaves the switch only;returnorexit()ends the program.- Keep persistent state outside the loop and validate every input.
- The same pattern becomes the super-loop and command shell in embedded firmware.
In the next lectures we apply control statements to larger practical problems: validating a calendar date, finding the gap between two dates and multiplying numbers using only doubling and halving. Keep following this free embedded C course to build real problem solving skill.
Frequently Asked Questions
Why use for(;;) instead of while(1)?
Both create an infinite loop and compile to the same machine code. for(;;) cannot trigger a “condition is always true” warning on some compilers, which is why many embedded coding standards prefer it.
Can I put a switch inside a for loop and a for loop inside a case?
Yes. Control statements nest freely, but keep each level readable and move long cases into functions.
What is the difference between exit(1) and return 1 in main?
Inside main they behave the same. exit() can also be called from any other function and needs stdlib.h, while return only leaves the function it is written in.
Why does my menu loop endlessly when I type a letter?
scanf fails and leaves the letter in the input buffer, so the next scanf fails again immediately. Check the return value and stop, or clear the buffer.
Do I need a default case?
It is not required by the language, but it is a strong habit. It gives feedback for invalid input and prevents silent failures.
Is this pattern used in real embedded C programming?
Yes. Firmware super-loops and UART command shells use the same structure, only without a Quit option.
Keep Learning C for Free
This lecture is part of the EmbeddedPathashala free C programming course built for students who want to move into embedded systems and Linux development.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments