🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Exit Nested Loops in C
Three ways to exit nested loops in C: goto, flag variables and function return, compared with a real ADC fault-search example from embedded C programming.
Sooner or later every firmware engineer needs to exit nested loops in C. You scan a two-dimensional table of sensor values, find the first bad one, and now you want to stop everything, not just the innermost loop. C has no labelled break like some other languages, so you must choose another technique. This lecture of our free C programming course compares three of them side by side using the same problem and the same data, so you can judge the trade-offs yourself.
It is also the practical payoff of the goto discussion in the earlier lectures of this free C tutorial. Whether you work on bare-metal microcontrollers or Linux, the choice you make here affects readability and safety in real embedded C programming, and it is a favourite topic in interviews for anyone taking a free embedded C course seriously.
What You Will Learn
- Why break only leaves the innermost loop
- How to exit nested loops in C with a single goto
- How to do it with a flag variable and where that gets clumsy
- How to do it by moving the loops into a function and returning
- How to choose between the three approaches
Prerequisites
You should know for and while loops, two-dimensional arrays, break, and the goto basics from the previous two lectures. Basic knowledge of functions and pointers helps for the third technique, but we explain each step.
The Problem: Break Leaves Only One Loop
A break statement terminates the nearest enclosing loop and nothing more. Watch what happens when we use it inside a double loop:
#include <stdio.h>
int main(void)
{
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (c == 1)
break;
printf("r=%d c=%d\n", r, c);
}
}
return 0;
}
r=0 c=0
r=1 c=0
r=2 c=0
Each time c reaches 1, the inner loop ends, but the outer loop carries on with the next row. If our intention was to stop the whole search at the first hit, this code is wrong, even though it compiles without a single warning.
What break does in nested loops
The Test Problem: Find the First ADC Fault
For all three solutions we use the same data: a 4 by 5 grid of ADC readings, four boards with five channels each. A reading above 400 counts as a fault. We want the first fault found in row-major order and the number of readings we examined.
| Row | Ch 0 | Ch 1 | Ch 2 | Ch 3 | Ch 4 |
|---|---|---|---|---|---|
| 0 | 120 | 130 | 125 | 128 | 131 |
| 1 | 122 | 127 | 480 | 129 | 126 |
| 2 | 119 | 133 | 124 | 590 | 130 |
| 3 | 121 | 126 | 128 | 127 | 125 |
The expected answer is row 1, column 2, value 480, after eight readings: five from row 0 and three from row 1. Notice that row 2 also contains a fault (590), which our code must not reach.
Technique 1: Exit Nested Loops in C With Goto
#include <stdio.h>
#define ROWS 4
#define COLS 5
int main(void)
{
int adc[ROWS][COLS] = {
{120, 130, 125, 128, 131},
{122, 127, 480, 129, 126},
{119, 133, 124, 590, 130},
{121, 126, 128, 127, 125}
};
int limit = 400, checks = 0;
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
checks++;
if (adc[r][c] > limit) {
printf("Fault at row %d col %d value %d\n", r, c, adc[r][c]);
goto found;
}
}
}
printf("No fault\n");
found:
printf("Checks made: %d\n", checks);
return 0;
}
$ gcc -std=c11 -Wall nested_goto.c -o nested_goto
$ ./nested_goto
Fault at row 1 col 2 value 480
Checks made: 8
One jump leaves both loops immediately, skipping the “No fault” message. The jump goes forward, it stays inside one function, and the label name found tells the reader what is happening. This is the textbook case where goto makes code simpler.
Technique 2: A Flag Variable
If your coding standard bans goto, you can carry the decision in a variable. Every loop that must stop needs to test the flag.
#include <stdio.h>
#define ROWS 4
#define COLS 5
int main(void)
{
int adc[ROWS][COLS] = {
{120, 130, 125, 128, 131},
{122, 127, 480, 129, 126},
{119, 133, 124, 590, 130},
{121, 126, 128, 127, 125}
};
int limit = 400, checks = 0, found = 0, fr = -1, fc = -1;
for (int r = 0; r < ROWS && !found; r++) {
for (int c = 0; c < COLS; c++) {
checks++;
if (adc[r][c] > limit) {
found = 1;
fr = r;
fc = c;
break;
}
}
}
if (found)
printf("Fault at row %d col %d value %d\n", fr, fc, adc[fr][fc]);
else
printf("No fault\n");
printf("Checks made: %d\n", checks);
return 0;
}
Fault at row 1 col 2 value 480
Checks made: 8
The result is identical. The inner break leaves the column loop, and the !found test in the outer loop condition stops the row loop. The cost: three extra variables, an extra condition evaluated once per row, and logic that is spread across two places. With three nested loops you would test the flag at two levels. The more loops you nest, the clumsier this approach becomes.
Flag technique: two exits needed
Technique 3: Move the Loops Into a Function
A return statement leaves every loop at once, so wrap the search in a function that reports what it found. This is usually the cleanest option when the search is a reusable idea.
#include <stdio.h>
#define ROWS 4
#define COLS 5
static int find_fault(int a[ROWS][COLS], int limit, int *row, int *col)
{
for (int r = 0; r < ROWS; r++)
for (int c = 0; c < COLS; c++)
if (a[r][c] > limit) {
*row = r;
*col = c;
return 1;
}
return 0;
}
int main(void)
{
int adc[ROWS][COLS] = {
{120, 130, 125, 128, 131},
{122, 127, 480, 129, 126},
{119, 133, 124, 590, 130},
{121, 126, 128, 127, 125}
};
int r, c;
if (find_fault(adc, 400, &r, &c))
printf("Fault at row %d col %d value %d\n", r, c, adc[r][c]);
else
printf("No fault\n");
return 0;
}
Fault at row 1 col 2 value 480
The function returns 1 for found and 0 for not found, and passes the position back through two pointers. The calling code becomes a single readable if. As a bonus, find_fault can be unit-tested on its own and reused for other limits. The only costs are a function call, and the need to pass the array and results, which for small embedded functions is negligible and often optimised away by inlining.
Comparing the Three Techniques
| Aspect | goto | Flag variable | Function return |
|---|---|---|---|
| Extra variables | None | Flag plus saved position | Output parameters |
| Readability with 2 loops | Good | Fair | Very good |
| Readability with 3+ loops | Good | Poor | Very good |
| Allowed by strict coding standards | Often not | Yes | Yes |
| Reusable and testable | No | No | Yes |
| Extra run-time work | None | One flag test per outer iteration | One call |
A practical decision rule: if the search can stand alone as a function, use the function. If it cannot, and your project allows goto, one forward goto to a well-named label is fine. If goto is forbidden and the function approach is awkward, use a flag but keep the number of loops small.
A Technique to Avoid
Some programmers force every loop counter to its limit value before breaking, for example setting r = ROWS; c = COLS;. It works, but it overwrites loop variables you may still need, hides intent, and breaks if the loop conditions ever change. Prefer one of the three clear methods above.
Real-World Uses
- Searching a calibration table for the first out-of-range entry.
- Scanning a keypad matrix and stopping at the first pressed key.
- Looking for a free slot in a two-dimensional buffer pool.
- Validating a configuration structure with several levels of lists.
Common Mistakes
- Expecting break to leave all loops.
- Forgetting to test the flag in the outer loop, so the outer loop keeps running.
- Reading the saved row and column when no fault was found; they still hold the initial -1 values.
- Placing the goto label before the loops, which creates an accidental backward jump.
- Returning a pointer to a local variable from the search function instead of copying results into output parameters.
Best Practices and Performance
- Initialise result variables to a safe value so the “not found” path is well-defined.
- Name the exit label after the event:
found,done,out. - Prefer a function when the loops form a logical operation on their own.
- All three techniques perform similarly; a modern compiler produces nearly identical machine code. Choose by clarity, not speed.
- Limit nesting to what you can explain in one sentence; deep nesting is a design smell in any language.
Summary and Key Takeaways
- break leaves only the innermost loop.
- To exit nested loops in C you can use goto, a flag, or a function return.
- goto is shortest, flags are standard-friendly but clumsy, and a function return is cleanest and reusable.
- All three printed the same fault: row 1, column 2, value 480.
- Choose based on readability and your project’s coding rules.
You have now covered the jump statements of this chapter. In the next lecture of our free C programming course we begin the switch statement, C’s multi-way decision tool.
Frequently Asked Questions
How do I exit nested loops in C?
Use a goto to a label after the loops, set a flag that every loop checks, or move the loops into a function and use return.
Does break exit all loops in C?
No. break only terminates the innermost loop or switch that contains it.
Does C have a labelled break?
No. Unlike some other languages, C has no labelled break or continue, so you need goto, flags or a function.
Is goto acceptable for leaving nested loops?
Many programmers consider it acceptable because it is clear and jumps forward, but check your coding standard first.
Which method is fastest?
They perform almost the same. A flag adds a tiny test per outer iteration, but the difference is negligible, so choose for readability.
Can I use these techniques on microcontrollers?
Yes. All three are plain C and work on any embedded target, from 8-bit parts to Cortex-M and Linux systems.
Free Embedded C Course on EmbeddedPathashala
Next in this free C tutorial: the switch statement, the clean way to write multi-way decisions in embedded C programming.

2 Comments