🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Infinite Loops in C
Why loops never stop, three classic bugs to avoid, and how embedded C programming uses endless loops on purpose.
An infinite loop is a loop that never terminates. In desktop programs it usually means a frozen program. In embedded C programming it is also the normal shape of firmware. This lecture of our free embedded C course teaches both sides: the three bugs that cause accidental endless loops, and the deliberate super loop that powers every microcontroller project. It is a practical lesson from our free C tutorial series.
What You Will Learn
- The definition of an infinite loop and the three conditions that decide whether a loop ends.
- Three classic mistakes: wrong counting direction, missing update, and assignment instead of comparison.
- How to catch these bugs with compiler warnings and debugging techniques.
- When an infinite loop is the right design, and how to structure a firmware main loop.
- How to keep an intentional endless loop safe with timeouts and watchdogs.
Prerequisites
You should know the for, while, and do while loops and the relational operators from earlier lectures in this free C programming course.
What Makes a Loop End?
A loop ends only when its condition becomes false, or when a break or return runs. For a well-behaved counting loop, three things must agree: a sensible starting value, a condition that can eventually become false, and an update that moves toward that condition. If any one of the three is wrong, the loop runs forever.
Mistake 1: Counting in the Wrong Direction
Look at for (int i = 0; i <= 5; i--). The condition says “continue while i is at most 5”. Starting at 0 and decreasing gives 0, -1, -2 and so on, which are always at most 5. The condition can never turn false. The fix is i++. On real hardware a signed counter would eventually overflow, but that is undefined behaviour for signed integers in C, so you can never rely on it as an exit.
Mistake 2: Nothing Changes the Loop Variable
In a for loop the update expression is built in. In while and do while loops you must write the update yourself, and forgetting it is easy. In int k = 1; while (k < 5) { ... } with no change to k, the condition stays true forever. Whenever you write a while loop, ask yourself immediately: “which statement changes the condition?”
Mistake 3: Assignment Instead of Comparison
The single equals sign assigns; the double equals sign compares. Writing while (n = 2) assigns 2 to n, and the value of an assignment expression is the assigned value, 2, which is non-zero and therefore true. The loop never ends, and n is overwritten on every test. This is one of the most famous beginner bugs, and compilers can detect it.
Demo: Seeing All Three Bugs Safely
Running a truly endless loop hangs your terminal, so this demo adds a guard counter that breaks out after a few passes. The loops themselves keep their bugs, so you can watch them misbehave.
#include <stdio.h>
int main(void)
{
int guard = 0;
/* bug 1: counter moves away from the limit */
for (int i = 0; i <= 5; i--)
{
if (++guard > 6) { printf("bug1 cut off by guard\n"); break; }
}
/* bug 2: nothing changes k */
guard = 0;
int k = 1;
while (k < 5)
{
if (++guard > 6) { printf("bug2 cut off by guard\n"); break; }
}
/* bug 3: assignment instead of comparison */
guard = 0;
int n = 0;
while (n = 2)
{
if (++guard > 6) { printf("bug3 cut off by guard, n=%d\n", n); break; }
}
return 0;
}
Build and Run
$ gcc -std=c17 -Wall -Wextra -o inf inf.c
inf.c: In function 'main':
inf.c:24:12: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
24 | while (n = 2)
| ^
$ ./inf
bug1 cut off by guard
bug2 cut off by guard
bug3 cut off by guard, n=2
The compiler flagged bug 3 on its own, which proves how valuable -Wall is. Bugs 1 and 2 are logical errors that no warning can reliably catch, so you must read your loops carefully.
| Bug | Symptom | Fix |
|---|---|---|
| i– with i <= 5 | Counter moves away from the limit | Use i++ |
| No update in while | Condition never changes | Add the update statement |
| while (n = 2) | Always true, n overwritten | Use while (n == 2) |
A Defensive Trick for Comparisons
Some programmers write the constant on the left: while (2 == n). If you accidentally type a single equals sign, the compiler stops with an error because you cannot assign to a constant. Readability suffers slightly, so many teams rely on compiler warnings instead. Pick one style and apply it consistently.
When an Infinite Loop Is Correct
Desktop programs end; firmware does not. After a microcontroller starts, it initialises its clock, pins, and peripherals, and then repeats the same job forever: read sensors, update state, drive outputs. Returning from main() in such a system would leave the processor with nothing to run. That is why nearly every embedded project, bare metal or RTOS-based, ends with an intentional endless loop, often called the super loop or main loop.
Super Loop Example
The next program imitates a super loop on a PC. It fakes a button and leaves after a few ticks so that it terminates in a demo. In real firmware you would delete the exit.
#include <stdio.h>
static int tick = 0;
static int read_button(void) { return tick == 4; } /* fake input */
int main(void)
{
for (;;)
{
tick++;
printf("tick %d: sample sensors\n", tick);
if (read_button())
{
puts("button seen, leaving the loop for this demo");
break;
}
}
return 0;
}
$ gcc -std=c17 -Wall -Wextra -o super super.c
$ ./super
tick 1: sample sensors
tick 2: sample sensors
tick 3: sample sensors
tick 4: sample sensors
button seen, leaving the loop for this demo
Making Endless Loops Safe
- Use a watchdog. A hardware watchdog timer resets the chip if the loop stops refreshing it, which recovers from accidental hangs.
- Add timeouts to waits. A loop that waits for a hardware flag should also count and give up after a limit.
- Mark shared flags volatile. A flag changed by an interrupt must be declared
volatile, or the compiler may read it once and loop forever. - Keep each pass short. The slower the loop, the slower the whole product responds.
| Situation | Endless loop? | Reason |
|---|---|---|
| Counting 1 to 10 on a PC | Never | Must finish |
| Bare-metal main loop | Intentional | Firmware has no operating system to return to |
| Waiting for a UART byte | Only with timeout | A broken wire would hang the device |
| Error trap after a fault | Often intentional | Stops in a known state for the debugger or watchdog |
Debugging a Stuck Loop
- Compile with
-Wall -Wextraand read every warning. - Print the loop variable and condition each pass, then stop the program with Ctrl+C.
- Use a debugger: pause the program and look at the variable values.
- On hardware, toggle a GPIO pin each pass and observe it with a logic analyser.
Common Mistakes and Troubleshooting
- Unsigned counting down.
for (unsigned i = 5; i >= 0; i--)never ends, because an unsigned value is always at least zero. It wraps to a huge number instead. - Floating-point counters. A loop on
x != 1.0with steps of 0.1 may never hit exactly 1.0. - Semicolon after while.
while (k < 5);loops forever with an empty body. - Flag not volatile. The optimiser removes the re-read of a flag set by an interrupt.
Best Practices
- Write
for (;;)for intentional endless loops and comment it. - Use
<instead of!=as loop conditions when counting. - Always know which statement makes the condition false.
- Enable the watchdog before entering the main loop in production firmware.
Summary and Key Takeaways
- A loop needs a start value, a condition, and an update that moves toward ending.
- Wrong direction, missing update, and assignment in the condition are the classic accidental infinite loops.
- Compiler warnings catch
while (n = 2), but logic bugs need careful reading. - Embedded firmware uses an intentional
for (;;)super loop protected by a watchdog.
That completes the theory of this chapter. The final lecture of this free C programming course chapter gives you a quiz and a set of interview questions to test everything.
Frequently Asked Questions
What is an infinite loop in C?
It is a loop whose condition never becomes false and that has no break or return, so it never ends.
Why does while (n = 2) never stop?
The single equals assigns 2 to n, and the value of the assignment is 2, which is non-zero and therefore true every time.
Why do embedded programs use infinite loops?
Firmware must keep running as long as the device is powered, so the main function ends with an endless loop that repeats the work forever.
Is for (;;) different from while (1)?
No. Both mean the same thing and compile to the same code. for (;;) is often preferred in embedded coding standards.
How can I stop a running infinite loop in the terminal?
Press Ctrl+C in the terminal to send an interrupt signal to the program.
What does a watchdog timer do?
It resets the microcontroller if the software does not refresh it within a set time, which recovers from accidental hangs.
Test Yourself in the Free C Programming Course
Ready to check your understanding? The next lecture has a quiz and interview questions covering all of chapter 5 loops.

2 Comments