🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Infinite Loop Bugs
Counter wrap-around, floating point comparison and stray semicolons: three hidden reasons for an infinite loop in C, with safe demos for embedded C programming.
A loop that never stops is one of the first bugs every beginner meets, and it still catches professionals. This lecture of our free C programming course explains how an infinite loop in C hides behind code that looks correct, and when an endless loop is exactly what you want in embedded C programming. Every program was compiled and run, and the output you see is real.
What You Will Learn
- Three less obvious reasons an infinite loop in C appears: counter wrap-around, floating point comparison and a stray semicolon
- How to prove each bug safely with a guard counter instead of freezing your terminal
- How the compiler warnings
-Wtype-limitsand-Wmisleading-indentationpoint at these bugs - When an infinite loop is the correct design, such as a command loop or an embedded super loop
- How to leave an intentional endless loop with
breakandgoto - Habits that keep this free C tutorial code safe on real microcontrollers
Prerequisites
while,do...whileandforloops from the earlier lectures of this free C programming course- Basic integer types such as
uint8_tfromstdint.h gccon Linux, macOS or WSL. Every program here was compiled with-std=c17 -Wall -Wextra
Why an Infinite Loop in C Keeps Running
A loop stops only when its condition becomes false. An infinite loop in C therefore means one of two things: the condition can never become false, or the code that should change the condition never runs. The previous lecture looked at the first family of mistakes. This lecture adds three bugs that fool even experienced programmers because the code looks perfectly reasonable when you read it.
| Bug | What looks fine | What really happens |
|---|---|---|
| Counter wrap-around | i <= 255 on an 8-bit variable | The variable can never exceed 255, so the test is always true |
| Float equality | x != 1.0f after adding 0.1f ten times | 0.1 has no exact binary form, so x jumps past 1.0 |
| Stray semicolon | while (n <= 3); | The semicolon is the whole loop body, so n never changes |
| Intentional loop | for (;;) | Runs forever by design and exits through break |
To keep the experiments safe, each demo below carries a small guard counter that forces a stop after a few passes. In real firmware you would not add the guard. The point of the guard is to let you watch the bug without pressing Ctrl+C.
Bug 1: Counter Wrap-Around Creates an Infinite Loop in C
Old textbooks show this bug with a 16-bit int that wraps from 32767 to -32768. On a modern PC an int is 32 bits, so the same example needs a much bigger number. Embedded targets bring the problem back immediately, because 8-bit and 16-bit counters are everywhere in register maps, timers and small buffers. The rule is simple: if a variable has a maximum value, a test that asks whether it is less than or equal to that maximum can never fail.
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint8_t level;
int guard = 0;
for (level = 250; level <= 255; level++) {
printf("level=%u\n", (unsigned)level);
if (++guard == 10) { /* safety stop for the demo */
printf("guard hit: loop would never end\n");
break;
}
}
return 0;
}
$ gcc -std=c17 -Wall -Wextra wrap8.c -o wrap8 && ./wrap8
level=250
level=251
level=252
level=253
level=254
level=255
level=0
level=1
level=2
level=3
guard hit: loop would never end
The compiler even tells you. With -Wextra GCC prints a warning that the comparison is always true because of the limited range of the data type. Treat that message as a bug report, not as noise.
$ gcc -std=c17 -Wall -Wextra wrap8.c -o wrap8
wrap8.c: In function 'main':
wrap8.c:9:29: warning: comparison is always true due to limited range of data type [-Wtype-limits]
Signed versus unsigned
Unsigned types such as uint8_t wrap around by definition, which is why the demo above behaves the same on every compiler. Signed overflow, for example int going past INT_MAX, is undefined behaviour in C. The compiler is allowed to assume it never happens, so the loop may behave in surprising ways. Avoid depending on either kind of wrap-around.
How to fix the wrap-around bug
- Use a wider type for the loop variable, for example
unsignedoruint16_t, when the limit equals the maximum of the narrow type. - Test with
<and a limit one larger than the last value you want, or count the iterations separately. - Compile with
-Wall -Wextraand read the warnings.
Bug 2: Floating Point Equality and the Infinite Loop in C
The second bug comes from comparing a float or double with == or !=. Decimal fractions such as 0.1 cannot be stored exactly in binary, so every addition adds a tiny error. After ten additions the total is close to 1.0 but not equal to it, and a test for x != 1.0f stays true forever.
#include <stdio.h>
int main(void)
{
float x = 0.0f;
int guard = 0;
while (x != 1.0f) {
printf("x=%.8f\n", x);
x += 0.1f;
if (++guard == 14) {
printf("guard hit: x never equals 1.0 exactly\n");
break;
}
}
return 0;
}
$ gcc -std=c17 -Wall -Wextra floatstep.c -o floatstep && ./floatstep
x=0.00000000
x=0.10000000
x=0.20000000
x=0.30000001
x=0.40000001
x=0.50000000
x=0.60000002
x=0.70000005
x=0.80000007
x=0.90000010
x=1.00000012
x=1.10000014
x=1.20000017
x=1.30000019
guard hit: x never equals 1.0 exactly
Look at the line that should have been 1.0. It prints 1.00000012, so the condition x != 1.0f is still true and the loop walks past the target. The same effect appears in a loop that adds 0.2 until it reaches 3.0.
Three safe ways to write the loop
| Fix | Idea | Good for |
|---|---|---|
| Integer counter | Count steps with an int and compute the value from the step | Fixed number of steps |
| Ordered test | Use < or <= instead of != so overshoot still ends the loop | Quick repair, but the final pass may be early or late by one |
| Tolerance | Stop when the absolute difference is smaller than a small epsilon | Values that come from real measurements |
The integer counter is the cleanest option because the count of steps is exact. A plain <= test on a float is not a complete cure: depending on rounding, the last step may run or may be skipped, so it should not be your first choice when you need an exact number of passes.
#include <stdio.h>
int main(void)
{
int step;
for (step = 0; step <= 10; step++)
printf("x=%.1f\n", step / 10.0);
return 0;
}
$ gcc -std=c17 -Wall -Wextra floatfix.c -o floatfix && ./floatfix
x=0.0
x=0.1
x=0.2
x=0.3
x=0.4
x=0.5
x=0.6
x=0.7
x=0.8
x=0.9
x=1.0
This version prints exactly eleven lines, from 0.0 to 1.0, every time. The loop variable is an integer, so the loop ends by exact arithmetic.
Bug 3: A Stray Semicolon Makes an Infinite Loop in C
The third bug is a single character. A semicolon directly after the closing parenthesis of while is an empty statement, and an empty statement is a perfectly valid loop body. The indented line below it is not part of the loop at all. The loop test never changes anything, so if it is true once, it stays true forever.
#include <stdio.h>
int main(void)
{
int n = 1;
while (n <= 3);
printf("%d\n", n++);
return 0;
}
GCC with -Wall recognises the pattern and warns about the misleading indentation:
$ gcc -std=c17 -Wall -Wextra semi.c -o semi
semi.c: In function 'main':
semi.c:7:5: warning: this 'while' clause does not guard... [-Wmisleading-indentation]
semi.c:8:9: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the 'while'
To confirm the hang without losing your terminal, run it under timeout. Exit code 124 means the command was stopped because it ran too long.
$ timeout 2 ./semi; echo "exit=$?"
exit=124
The repaired program uses braces and updates the counter inside the loop:
#include <stdio.h>
int main(void)
{
int n = 1;
while (n <= 3) {
printf("%d\n", n);
n++;
}
return 0;
}
$ gcc -std=c17 -Wall -Wextra semifix.c -o semifix && ./semifix
1
2
3
Intentional Infinite Loops in C
Not every endless loop is a mistake. A menu program, a network server and the main function of almost every firmware image should keep running until something tells it to stop. C gives you three common spellings, and all three do the same job.
| Form | Why it is endless | Where you see it |
|---|---|---|
while (1) | The constant 1 is always true | Most common in firmware super loops |
for (;;) | An empty condition is treated as true | Popular in C code from the Unix world |
do { ... } while (1); | Body runs first, test is always true | Rare, used when the body must run once |
The loop below acts like a tiny command interpreter. It reads commands from a fixed script instead of the keyboard, so the output is the same every time you run it. The endless loop ends only when the quit command appears.
#include <stdio.h>
int main(void)
{
const char script[] = {'s', 'r', 'x', 'r', 'q', 's'};
int pos = 0;
for (;;) {
char cmd = script[pos++];
if (cmd == 'q') {
printf("quit command: leaving the loop\n");
break;
}
switch (cmd) {
case 's': printf("status: all good\n"); break;
case 'r': printf("reset: counters zero\n"); break;
default: printf("unknown command '%c'\n", cmd); break;
}
}
printf("shutdown\n");
return 0;
}
$ gcc -std=c17 -Wall -Wextra cmdloop.c -o cmdloop && ./cmdloop
status: all good
reset: counters zero
unknown command 'x'
reset: counters zero
quit command: leaving the loop
shutdown
The embedded super loop
A bare-metal microcontroller has no operating system to return to. After the start-up code initialises the clocks and peripherals, main enters a while (1) loop that reads inputs, makes decisions and drives outputs. If main ever returned, the processor would run off into unknown memory. For that reason an endless loop is not only allowed in embedded C programming, it is required.
Leaving a nested loop early with goto
A break leaves only the innermost loop. When a fault is found deep inside two loops and you want to leave both at once, a single forward goto to a clearly named label is an accepted pattern in C.
#include <stdio.h>
int main(void)
{
int row, col;
for (row = 0; row < 3; row++) {
for (col = 0; col < 3; col++) {
if (row == 1 && col == 2) {
printf("fault at row %d col %d\n", row, col);
goto stop;
}
printf("ok %d,%d\n", row, col);
}
}
stop:
printf("scan ended\n");
return 0;
}
$ gcc -std=c17 -Wall -Wextra gotoout.c -o gotoout && ./gotoout
ok 0,0
ok 0,1
ok 0,2
ok 1,0
ok 1,1
fault at row 1 col 2
scan ended
Common Mistakes and Troubleshooting
| Symptom | Likely cause | What to check |
|---|---|---|
| Program hangs with no output | Empty body from a stray ; | Look for while (...); or for (...); |
| Counter restarts from 0 | Loop variable type too small | Compare the limit with the maximum of the type |
| Float loop runs one pass too many | != or == used on floating point | Switch to an integer counter |
| Output repeats the same line | Update statement missing or skipped | Print the loop variable each pass |
| Loop never reaches a later statement | Exit condition tests the wrong variable | Write the exit condition in words first |
Best Practices
- Always use braces, even for one statement. A semicolon mistake is much harder to make that way.
- Never test floating point values with
==or!=. Count with integers. - Pick a loop variable type large enough for the limit, and prefer
unsignedorsize_tfor sizes. - Enable
-Wall -Wextraand treat warnings as errors in your build. - Give every intentional endless loop exactly one clearly commented exit path, or document that it never exits.
Performance and safety notes
A tight endless loop that does nothing keeps the processor at full speed and drains a battery. In low-power firmware, put the processor to sleep inside the loop and wake it with an interrupt. A hung loop on a real device is also a safety problem, which is why production firmware usually enables a hardware watchdog timer that resets the chip if the main loop stops running.
Summary and Key Takeaways
- A loop ends only when its condition becomes false, so any bug that freezes the condition creates an infinite loop in C.
- A narrow variable cannot exceed its maximum, so
i <= maxis always true. - Floating point values accumulate rounding errors. Use an integer counter for exact repetition.
- A semicolon after
while (...)is an empty loop body. while (1)andfor (;;)are the standard intentional endless loops. Leave them withbreakorgoto.
Conclusion
The three bugs in this lecture share a pattern: the code reads well but the machine does something different. Training yourself to read a loop as the compiler does, and letting warnings help, will save hours in debugging. In the next lecture of this free C programming course we study the break statement properly, including how it behaves in nested loops and inside switch.
Frequently Asked Questions
What is an infinite loop in C?
A loop whose condition never becomes false, or whose update code never runs, so it does not stop by itself. It can be a bug or a deliberate design.
How do I stop an infinite loop in my terminal?
Press Ctrl+C. To run a test program safely, start it with timeout 2 ./program, which stops it after two seconds.
Why does comparing floats with == cause trouble?
Many decimal fractions such as 0.1 cannot be stored exactly in binary, so repeated additions drift away from the expected value.
Is while(1) or for(;;) better?
They behave the same. Pick one style for the whole project. Many embedded teams prefer while (1) for readability.
Is an infinite loop used in embedded C programming?
Yes. Bare-metal firmware normally runs a while (1) super loop in main because there is no operating system to return to.
Does a semicolon after while always create an infinite loop?
Only if the condition stays true. The empty body can never change it, so a true condition stays true. A false condition simply skips the loop.
Is this a free C tutorial for beginners?
Yes. This free C programming course is written for students and covers C for embedded systems from the basics.
Keep learning with the free C course
EmbeddedPathashala teaches C programming for embedded systems for free, one small lecture at a time. Move on to the next lecture, or revisit the previous one and run the programs yourself.

2 Comments