Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
C Loop Mistakes to Avoid
Five loop bugs every beginner hits, reproduced safely with gcc and fixed with simple habits.
The common C loop mistakes are the same few errors repeated by every beginner and, honestly, by plenty of experienced engineers at 2 a.m. An accumulator that was never initialised, a condition that can never become false, an assignment typed where a comparison was meant, a data loop with no exit: each one compiles cleanly and fails at run time. In this lecture of our free C programming course we take five of these mistakes, reproduce them safely, read the compiler messages and learn the habit that prevents each one. This is core embedded C programming knowledge, because on a microcontroller an endless loop does not just hang a terminal, it can reset the whole device.
What You Will Learn
- Why an uninitialised accumulator gives unpredictable totals
- How an empty for header and a zero-or-nonzero test can overshoot and never stop
- Why
while (x = y)is legal C and what gcc says about it - How to stop an input loop on a limit and on end of input
- What post-increment inside a condition does to the final counter value
- A checklist you can apply to any loop before you run it
Prerequisites
You should know the for, while and do-while loops, the relational and assignment operators, and how to compile and run a C file with gcc. The previous two lectures on the continue statement and on scope are helpful but not required for this free C tutorial.
A Quick Map of the Common C Loop Mistakes
| # | Mistake | What you see | Prevention |
|---|---|---|---|
| 1 | Accumulator not initialised | Random or wrong total | Initialise at declaration |
| 2 | Condition can be skipped over | Loop never ends or overshoots | Use > or < instead of testing for exact zero |
| 3 | Assignment instead of comparison | Loop ends at a strange moment, variable changed | Use == and compile with -Wall |
| 4 | No exit on input loops | Endless loop at end of input | Check scanf result and add a limit |
| 5 | Post-increment surprise | Counter one higher than expected | Trace the value before and after the test |
Five checks before you trust any loop
Mistake 1: The Uninitialised Accumulator
An accumulator is a variable that collects a running total, such as total += i * i. If you declare it with int total; and never give it a value, it holds whatever happened to be in that stack slot or register. Reading it is undefined behaviour in C, so one run may print a plausible number and the next run may print garbage. That unpredictability is what makes this one of the most annoying common C loop mistakes: the code looks fine.
Here is the correct version. It also shows how a step of 4 changes the visited values:
File: accum.c
#include <stdio.h>
int main(void)
{
int i;
int total = 0; /* remove "= 0" and the result is garbage */
for (i = 0; i < 12; i += 4) {
total += i * i;
printf("i = %2d total = %3d\n", i, total);
}
printf("loop ended with i = %d\n", i);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o accum accum.c
$ ./accum
i = 0 total = 0
i = 4 total = 16
i = 8 total = 80
loop ended with i = 12Hand trace with a step of 4
| Round | i | i * i | total |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 4 | 16 | 16 |
| 3 | 8 | 64 | 80 |
| End | 12 | test 12 < 12 fails | 80 |
Remove the = 0 and the first addition starts from garbage. Compile with -Wall -Wextra and gcc can warn that the variable may be used uninitialised, especially when optimisation is enabled, but not in every situation, so do not rely on the warning alone. Also note the final counter: the loop ended with i = 12, not 8, because the update runs before the failing test.
Mistake 2: A Condition That Can Be Skipped Over
An empty first or third part in a for header is legal, and a bare variable is a legal condition because C treats zero as false and every other value as true. Combine the two and you get loops like for (; budget; ). That works only if the variable lands exactly on zero. If it jumps past zero, it is nonzero again and the loop keeps going.
File: empty.c
#include <stdio.h>
int main(void)
{
int budget = 30;
puts("step 10, test is just 'budget':");
for (; budget; )
printf("budget = %d\n", budget -= 10);
puts("step 7, test is 'budget > 0':");
budget = 30;
while (budget > 0)
printf("budget = %d\n", budget -= 7);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o empty empty.c
$ ./empty
step 10, test is just 'budget':
budget = 20
budget = 10
budget = 0
step 7, test is 'budget > 0':
budget = 23
budget = 16
budget = 9
budget = 2
budget = -5With a step of 10 the budget goes 30, 20, 10, 0 and the bare test stops it. With a step of 7 it goes 30, 23, 16, 9, 2 and then overshoots to -5. A bare test would have accepted -5 as true and kept subtracting for ever, which is why the second loop uses budget > 0. Even the safe version shows a subtle flaw: it printed -5, a value below zero, because the subtraction happens inside the printf. Decide whether you want the check before or after the update, and write it that way on purpose.
Rule to remember
Use >, <, >= or <= when a counter moves in steps. Reserve “test for exactly zero” for variables that change by one.
Mistake 3: Assignment Where Comparison Was Meant
In C an assignment is an expression whose value is the value that was assigned. So while (x = y) assigns y to x and then tests that value. It is valid, compiles, and does something different from while (x == y). Sometimes it is even intentional, but you should make the intent obvious.
File: assign.c
#include <stdio.h>
int main(void)
{
int x = 8, y = 6;
while (x = y) { /* assignment, NOT comparison */
printf("x = %d, y = %d\n", x, y);
y -= 2;
}
printf("exit: x = %d, y = %d\n", x, y);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o assign assign.c
assign.c: In function ‘main’:
assign.c:7:12: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
7 | while (x = y) { /* assignment, NOT comparison */
| ^
$ ./assign
x = 6, y = 6
x = 4, y = 4
x = 2, y = 2
exit: x = 0, y = 0The compiler warning is the lesson: gcc suggests parentheses around the assignment, because that is the standard way to say “yes, I meant it”. Each pass copies y into x, prints them, then lowers y by 2. The loop ends only when the copied value is 0, so x and y are always equal inside the body. If you want an intentional assignment, write while ((x = y) != 0) so the next reader does not have to guess.
Warning: never ignore the message “suggest parentheses around assignment used as truth value”. In a real driver the same typo in an if statement can silently overwrite a status variable.
Mistake 4: Input Loops With No Exit
Loops that read numbers until some condition are everywhere in embedded tools: reading a serial log, parsing a file, accepting commands. The mistake is to loop on scanf without checking what it returned, or to forget the exit condition entirely. scanf returns the number of items it successfully read, and when the input ends or is invalid it returns something else, so test for the exact number you expect.
File: limit.c
#include <stdio.h>
int main(void)
{
int value, total = 0, entries = 0;
while (scanf("%d", &value) == 1) { /* stops on EOF or bad input */
total += value;
entries++;
if (total > 100)
break;
}
printf("entries = %d, total = %d\n", entries, total);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o limit limit.c
$ echo "40 35 30 10" | ./limit
entries = 3, total = 105
$ echo "10 20" | ./limit
entries = 2, total = 30Run 1: input 40 35 30 10
| Read | Total after adding | Total > 100 ? | Action |
|---|---|---|---|
| 40 | 40 | no | continue reading |
| 35 | 75 | no | continue reading |
| 30 | 105 | yes | break, 10 is never read |
The first run stops through the break when the total exceeds 100, with three entries. The second run never reaches the limit: after reading 10 and 20 the input ends, scanf returns something other than 1, and the loop condition itself ends the loop. If the condition were simply while (1) and the program ignored the return value, the second run would loop forever on a closed input, one of the most damaging common C loop mistakes in tools that parse files.
Mistake 5: The Post-Increment Surprise
The expression k++ < 3 compares the old value of k and increments afterwards, whether the test passes or not. That means the counter ends one higher than many students predict.
File: postinc.c
#include <stdio.h>
int main(void)
{
int k = 0;
while (k++ < 3)
printf("inside : k = %d\n", k);
printf("after : k = %d\n", k);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o postinc postinc.c
$ ./postinc
inside : k = 1
inside : k = 2
inside : k = 3
after : k = 4Trace of while (k++ < 3)
| Test | k compared | Result | k after test | Body runs? |
|---|---|---|---|---|
| 1 | 0 | true | 1 | yes, prints 1 |
| 2 | 1 | true | 2 | yes, prints 2 |
| 3 | 2 | true | 3 | yes, prints 3 |
| 4 | 3 | false | 4 | no |
The failing fourth test still increments k to 4, so the value after the loop is 4. Use this knowledge, or avoid the pattern entirely by incrementing inside the body where it is easier to see.
Embedded Systems Angle: Polling Loops and Watchdogs
In firmware you often write loops that wait for a hardware flag. The common C loop mistakes above become more dangerous there. A loop that never ends will either freeze the device or trigger the hardware watchdog, producing a reset that looks random. Two habits help. First, give every waiting loop a timeout counter so that it always ends and can report an error. Second, read hardware registers through a pointer declared volatile, otherwise the compiler may read the flag once and loop on the stale value. Neither habit is exotic; they are simply the loop checklist from earlier applied to real hardware.
Debugging Tips for Common C Loop Mistakes
- Print the loop variable at the top of the body for a few iterations, then remove the print.
- Compile with
-Wall -Wextra, and add-Wshadowif nested loops are involved. - Run suspect programs under
timeout 2so that an endless loop cannot lock your terminal. - Trace the first three and the last two iterations by hand in a table.
- Use a debugger such as gdb: set a breakpoint inside the loop and watch the condition variable change.
Best Practices to Avoid Common C Loop Mistakes
- Initialise at declaration. Make it a reflex for counters, sums and flags.
- Prefer relational tests to exact equality when the counter moves in steps larger than one.
- Write comparisons the careful way. Some teams put the constant on the left, as in
0 == x, so a single equals sign becomes a compile error. - Always bound your loops. A limit, a timeout or an end-of-input check keeps every loop finite.
- Performance: a loop condition is evaluated every iteration, so keep it cheap; do not call a slow function in the test if the result does not change.
- Security: unbounded input loops are a classic source of buffer overflows and denial of service. Validate counts and sizes before writing into arrays.
Summary and Key Takeaways
- Uninitialised accumulators give undefined results; always set them at declaration.
- A bare zero-or-nonzero test only stops a loop that lands exactly on zero.
- Assignment inside a condition is legal; gcc warns you, and parentheses state the intent.
- Input loops need both a limit and a check of what scanf returned.
- Post-increment in a condition leaves the counter one higher than the last body value.
Conclusion
None of these common C loop mistakes needs advanced knowledge to fix. They need a checklist and the discipline to trace a loop by hand before running it. Apply the five checks from this lecture to every loop you write, and your firmware will be calmer and your exam answers more accurate. The next lecture covers the rules of the switch statement, including why continue is allowed in some places and not in others. It continues this free embedded C course in the order a professional would learn it.
Frequently Asked Questions
What are the most common C loop mistakes?
Forgetting to initialise accumulators, writing conditions that can be skipped over, using = instead of ==, loops with no exit condition and misunderstanding post-increment in a condition.
Why does while (x = y) compile in C?
Because assignment is an expression whose value is the assigned value, so it is a valid condition. gcc warns about it so you can add parentheses or fix the typo.
What happens if I do not initialise a sum variable in a loop?
It holds an indeterminate value and using it is undefined behaviour. The result may differ between runs and compilers.
How do I stop an endless loop in the terminal?
Press Ctrl+C. To be safe when testing risky code, run it as timeout 2 ./program so it is killed automatically.
Why does a loop with i += 7 and a bare condition never end?
A bare condition is true for any nonzero value. If the counter jumps over zero it never equals zero again, so the loop keeps running. Use a greater-than test instead.
How should I read integers in a loop safely?
Check that scanf returns the number of items you expect, and stop on failure or end of input. Add a limit as well so a bad file cannot run the loop forever.
Why is the counter one higher than expected after while (k++ < 3)?
The increment happens after every comparison, including the final failing one, so k ends at 4.
How do embedded engineers prevent endless loops?
They add timeouts to polling loops, use volatile for hardware registers and rely on a watchdog timer as a last line of defence.
Keep Going With the Free C Course
This free C tutorial builds the loop discipline that embedded C programming demands. Continue to the next lecture on switch statements.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments