🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →For Loop in Embedded C: Syntax, Execution Order, Off-by-One, Unsigned Traps and Delay Loops
The three parts of a for loop and their order, counting up and down, off-by-one errors, the unsigned decrement trap, header variations, floating-point counters, arrays, delay loops with volatile, embedded patterns and performance. Keep this in mind whenever you write a for loop in embedded C.
What You Will Learn
for loop and the exact order in which they run< versus <= and how to test themi >= 0 never endsfor (;;) and the comma operatorvolatile, and what the optimiser does to an empty loopKey Terms
1. Why Loops?
Embedded programs repeat things constantly. They scan 16 ADC channels, clear a 256-byte buffer, shift out 8 bits of a SPI byte, blink four LEDs in turn, wait for a flag, and, above all, run the main program forever. The for loop in embedded C is the loop you use when you know, or can compute, how many times to repeat. It packs the setup, the test and the step into a single header line so that the control logic of the loop sits in one place. Many bugs in a for loop in embedded C start here.
| Part | When it runs | Typical content |
|---|---|---|
| initialisation | Once, before the first test | int i = 0 |
| condition | Before every iteration, including the first. If it is false (zero) the loop ends. | i < 10 |
| body | Each time the condition was true | your statements |
| update | After every execution of the body, then back to the condition | i++ |
↓
↓
Remember the order: init, test, body, update, test, body, update … test (false), exit. The update is not run when the test fails, so after a normal loop for (i = 0; i < 5; i++) the variable holds 5, not 4. This is the core rule of the for loop in embedded C.
2. Your First for Loops
Notice the last value of j: 5. The loop stops when the test j < 5 becomes false, and that happens with j already incremented to 5. Code after a loop that uses the counter must account for this.
Execution trace
The table traces for (i = 0; i < 3; i++) sum += i; with sum starting at 0:
| Step | Action | i | Test | sum |
|---|---|---|---|---|
| 1 | init | 0 | 0 | |
| 2 | test i < 3 | 0 | true | 0 |
| 3 | body | 0 | 0 | |
| 4 | update | 1 | 0 | |
| 5 | test i < 3 | 1 | true | 0 |
| 6 | body | 1 | 1 | |
| 7 | update | 2 | 1 | |
| 8 | test | 2 | true | 1 |
| 9 | body | 2 | 3 | |
| 10 | update | 3 | 3 | |
| 11 | test | 3 | false | 3 (exit) |
3. Off-by-One Errors
The most frequent loop bug is running one time too many or too few. For n repetitions starting from zero the standard pattern is for (i = 0; i < n; i++). Using <= gives n + 1 passes and, on an array, one access past the end.
| Goal | Correct header | Common wrong form |
|---|---|---|
| n passes, index 0..n-1 | for (i = 0; i < n; i++) | i <= n (n + 1 passes) |
| values 1..n inclusive | for (i = 1; i <= n; i++) | i < n (misses n) |
| n passes counting down | for (i = n; i > 0; i--) | i >= 0 (n + 1 passes) |
| visit every element of a[N] | for (i = 0; i < N; i++) | i <= N (buffer overrun) |
4. Counting Down and the Unsigned Trap
Reversing an array or counting down to zero seems easy, but an unsigned loop counter can never become negative. The test i >= 0 is therefore always true, and when i is 0 the decrement wraps to 4294967295 (for a 32-bit unsigned). On a Cortex-M4 the loop would run through memory until a fault occurs.
for (i = n; i-- > 0; ): The test compares the old value of i with zero and decrements it at the same time. The body sees i from n – 1 down to 0, and the loop ends after the test of 0 without ever wrapping.5. Variations of the for Header
Every part of the header is optional, and each can contain any expression. The semicolons are mandatory.
| Form | Meaning |
|---|---|
for (;;) | Infinite loop: no condition means true. The embedded super loop. |
for (; i < n; i++) | Initialisation done before the loop, e.g. when the start value is computed. |
for (i = 0; i < n; ) | Update done inside the body, e.g. when it depends on what was read. |
for (int i = 0, j = 9; i < j; i++, j--) | Two variables with the comma operator in the update; the declaration is a list, not a comma operator. |
for (p = head; p != NULL; p = p->next) | Walks a linked list; the condition tests a pointer. |
for (int i = 0; i < n; i++); | Stray semicolon: empty body. The statement after it runs once. |
Scope of the loop variable
Since C99 the initialisation may declare a variable. Its scope is the loop only, so the name can be reused afterwards and it cannot be used after the loop. This is the preferred style: it prevents accidental reuse of a stale counter. Old compilers or strict C89 mode need the declaration before the loop; in GCC use -std=gnu11 or later (the default).
6. Floating-Point Loop Counters
A floating-point variable as a loop counter accumulates rounding error, so the number of passes may be different from what you expect. Use an integer counter and compute the floating value from it.
The float variable never hits exactly 1.0 because 0.1 has no exact binary representation, so the != test is never false and the loop would not end without the safety exit. The integer version always makes 11 passes.
7. Arrays and Loops
Loops and arrays belong together. The element count should come from sizeof, never from a copied number, so that the loop follows the array when its size changes (Lesson 5.4).
size_t is the unsigned type of sizeof, so comparing it with COUNT_OF() mixes no signed and unsigned values. If a loop must go below zero, use the forms of section 4.8. Delay Loops and the Optimiser
A beginner’s first delay is an empty loop: for (i = 0; i < 1000000; i++);. It looks like a delay, but with optimisation on the compiler may delete it, because it has no observable effect. This is the real GCC -O2 output for two versions (x86-64 shown; the Cortex-M4 result is the same in principle):
volatile forces every access to memory, so the loop survives. Even so, a software delay is unreliable: the time per pass changes with the optimisation level, the flash wait states, the clock frequency and any interrupt that occurs during the loop. For accurate delays use a hardware timer (SysTick, TIM2) or the DWT cycle counter.
| Method | Accuracy | CPU use | Use for |
|---|---|---|---|
| Empty loop | Poor, changes with compiler and clock | 100% | Very short settling delays only |
volatile counter loop | Poor to fair | 100% | Rough startup waits |
SysTick polling (HAL_Delay) | Good (1 ms ticks) | 100% while waiting | Simple programs |
| Timer interrupt or low-power wait | Excellent | Almost none | Production code |
9. Embedded Uses of the for Loop
| Job | Loop | Note |
|---|---|---|
| Clear a buffer | for (i = 0; i < N; i++) buf[i] = 0; | Or memset, usually faster |
| Scan ADC channels 0..15 | for (ch = 0; ch < 16; ch++) | Fixed trip count |
| Send 8 bits MSB first (software SPI) | for (b = 7; b >= 0; b--) | Use a signed b |
| Chase the 4 LEDs PD12..PD15 | for (p = 12; p <= 15; p++) | Mask is 1u << p |
| Bitwise CRC | inner loop over 8 bits per byte | Table lookup is faster |
| Main program | for (;;) { ... } | Never returns |
| Timeout while polling a flag | for (n = TIMEOUT; n > 0 && !(SR & RDY); n--) | Always bound the wait |
10. Loop Performance on the Cortex-M4
- Loop-invariant code: move calculations that do not change out of the loop, and never call
strlen(s)in the condition of a loop that does not change s. Each test would rescan the whole string (n squared overall). - Count down to zero: on ARM the decrement sets the flags, so
for (n = N; n != 0; n--)needs no separate compare instruction. Compilers often do this transformation by themselves at -O2. - Unrolling: doing 4 elements per pass cuts loop overhead, but increases code size;
-O3or#pragma GCC unroll 4can do it for you. - Use library or hardware:
memcpy,memset, DMA and the CMSIS-DSP functions beat hand loops for bulk data. - Keep it simple: measure with the DWT cycle counter before optimising.
11. Common Mistakes
for (...); makes the body empty. GCC’s -Wmisleading-indentation reports it only when the next line is indented as if it were the body, so review carefully.<= instead of < on array bounds: Reads or writes one element past the end.>= 0: The loop never ends.12. Best Practices for the for loop in Embedded C
- Declare the counter in the header:
for (size_t i = 0; ...). - Use
i < Nwith the count fromsizeof. - Do not modify the counter in the body (MISRA C:2012 rule 14.2).
- Use integer counters, not floating-point (MISRA rule 14.1).
- Keep the header simple: one counter, one test, one step.
- Write braces around the body, even for a single statement.
- Bound every wait on hardware with a timeout.
- Use timers, not loops, for time delays.
Key Takeaways — Lesson 7.1
- The for loop in embedded C is init, test, body, update, repeated until the test fails.
- After a normal exit the counter holds the first value that failed the test.
i < nfrom 0 gives exactly n passes.- Unsigned counters need
i-- > 0or an offset, neveri >= 0. for (;;)is the standard infinite loop of embedded main functions.- Floating-point counters accumulate error; derive the value from an integer.
- An empty delay loop needs
volatile, and still is not a reliable timer.
Frequently Asked Questions
Ready to practise?
Next: worked examples with LED chases, ADC averaging, software SPI, reversing arrays and timeouts on real output.

2 Comments