Theory- For Loop in Embedded C: Syntax, Execution Order, Off-by-One, Unsigned Traps and Delay Loops-Free Embedded C Programming Course

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

MODULE 7 · LESSON 7.1 · THEORY

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.

55 min
Read Time
Beginner
Level
M7 · L1
Module / Lesson

What You Will Learn

✓ The three parts of a for loop and the exact order in which they run
✓ Counting up, counting down and stepping by more than one
✓ Off-by-one errors with < versus <= and how to test them
✓ The unsigned down-counting trap: why i >= 0 never ends
✓ Loop variable scope, empty parts, for (;;) and the comma operator
✓ Floating-point loop counters and why to avoid them
✓ Delay loops, volatile, and what the optimiser does to an empty loop
✓ Performance: loop-invariant code, counting to zero and unrolling

Key Terms

forInitialisationConditionUpdateIterationLoop variableOff-by-oneInfinite loopSuper loopDelay loopvolatileLoop unrollingLoop-invariantSentinelTrip count

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.

Syntax of the for loop
for (initialisation; condition; update) { body; }
PartWhen it runsTypical content
initialisationOnce, before the first testint i = 0
conditionBefore every iteration, including the first. If it is false (zero) the loop ends.i < 10
bodyEach time the condition was trueyour statements
updateAfter every execution of the body, then back to the conditioni++
Order of execution of a for loop
1. initialisation
runs once
↓
2. condition ?
tested before every pass
true
↓
3. body
↓
4. update
then back to 2
false
↓
leave the loop
continue after the loop

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

for_basic.c
#include <stdio.h> int main(void) { printf(“count up : “); for (int i = 0; i < 5; i++) printf(“%d “, i); printf(“\n”); printf(“count down: “); for (int i = 5; i > 0; i–) printf(“%d “, i); printf(“\n”); printf(“step by 3 : “); for (int i = 0; i <= 15; i += 3) printf(“%d “, i); printf(“\n”); int j; for (j = 0; j < 5; j++) ; /* empty body: only the counting matters */ printf(“after the loop j = %d\n”, j); int sum = 0; for (int i = 1; i <= 10; i++) sum += i; printf(“sum 1..10 = %d\n”, sum); return 0; }
Output (verified by compiling and running)
count up : 0 1 2 3 4 count down: 5 4 3 2 1 step by 3 : 0 3 6 9 12 15 after the loop j = 5 sum 1..10 = 55

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:

StepActioniTestsum
1init00
2test i < 30true0
3body00
4update10
5test i < 31true0
6body11
7update21
8test2true1
9body23
10update33
11test3false3 (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.

off_by_one.c
#include <stdio.h> int main(void) { int n = 4; int count_lt = 0, count_le = 0; for (int i = 0; i < n; i++) count_lt++; for (int i = 0; i <= n; i++) count_le++; printf(“i < %d runs %d times\n”, n, count_lt); printf(“i <= %d runs %d times\n”, n, count_le); int a[4] = { 10, 20, 30, 40 }; int total = 0; for (int i = 0; i < 4; i++) total += a[i]; printf(“sum of 4 elements = %d\n”, total); return 0; }
Output (verified by compiling and running)
i < 4 runs 4 times i <= 4 runs 5 times sum of 4 elements = 100
GoalCorrect headerCommon wrong form
n passes, index 0..n-1for (i = 0; i < n; i++)i <= n (n + 1 passes)
values 1..n inclusivefor (i = 1; i <= n; i++)i < n (misses n)
n passes counting downfor (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)
Embedded consequence: An overrun by one element writes into the next variable in RAM. There is no operating system to stop you; the corruption shows up later as a strange bug. Test the first, the last and one-past-last index.

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.

unsigned_trap.c
#include <stdio.h> #include <stddef.h> int main(void) { unsigned a[4] = { 1, 2, 3, 4 }; /* WRONG: for (unsigned i = 3; i >= 0; i–) never ends. Safe forms: */ printf(“form 1 (signed counter) : “); for (int i = 3; i >= 0; i–) printf(“%u “, a[i]); printf(“\n”); printf(“form 2 (test then decrement): “); for (size_t i = 4; i– > 0; ) printf(“%u “, a[i]); printf(“\n”); printf(“form 3 (count n down to 1) : “); for (size_t k = 4; k > 0; k–) printf(“%u “, a[k – 1]); printf(“\n”); return 0; }
Output (verified by compiling and running)
form 1 (signed counter) : 4 3 2 1 form 2 (test then decrement): 4 3 2 1 form 3 (count n down to 1) : 4 3 2 1
bad_unsigned.c
#include <stdio.h> int main(void) { unsigned count = 0; for (unsigned i = 3; i >= 0; i–) { if (++count > 5) break; } printf(“%u\n”, count); return 0; }
GCC (-Wextra) warns about the always-true test
bad_unsigned.c: In function ‘main’: bad_unsigned.c:5:28: warning: comparison of unsigned expression in ‘>= 0’ is always true [-Wtype-limits] 5 | for (unsigned i = 3; i >= 0; i–) | ^~
The idiom 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.

FormMeaning
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.
for_variants.c
#include <stdio.h> int main(void) { int a[6] = { 1, 2, 3, 4, 5, 6 }; for (int i = 0, j = 5; i < j; i++, j–) /* reverse in place */ { int t = a[i]; a[i] = a[j]; a[j] = t; } for (int i = 0; i < 6; i++) printf(“%d “, a[i]); printf(“\n”); int i = 0; for (; i < 10; ) /* update inside the body */ { i += (i < 4) ? 1 : 3; printf(“i=%d “, i); } printf(“\n”); int counter = 0; for (;;) /* super loop with a controlled exit */ { if (++counter == 3) break; } printf(“left the infinite loop at counter=%d\n”, counter); for (int k = 0; k < 3; k++); /* stray semicolon */ { printf(“this block runs only once\n”); } return 0; }
Output (verified by compiling and running)
6 5 4 3 2 1 i=1 i=2 i=3 i=4 i=7 i=10 left the infinite loop at counter=3 this block runs only 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.

float_loop.c
#include <stdio.h> int main(void) { int passes = 0; for (float x = 0.0f; x != 1.0f; x += 0.1f) /* test with != is dangerous */ { passes++; if (passes > 20) break; /* safety exit for the demo */ } printf(“float counter stepping 0.1 : %d passes before the safety exit\n”, passes); int n = 0; for (int k = 0; k <= 10; k++) { float x = (float)k / 10.0f; /* derived from an integer */ n++; if (k == 3) printf(“k=3 gives x=%.1f\n”, x); } printf(“integer counter : %d passes\n”, n); return 0; }
Output (verified by compiling and running)
float counter stepping 0.1 : 21 passes before the safety exit k=3 gives x=0.3 integer counter : 11 passes

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).

array_loops.c
#include <stdio.h> #include <stdint.h> #define COUNT_OF(a) (sizeof(a) / sizeof((a)[0])) int main(void) { uint16_t adc[] = { 2048, 2051, 2043, 2060, 2049, 2055, 2047, 2052 }; size_t n = COUNT_OF(adc); uint32_t sum = 0; uint16_t min = adc[0], max = adc[0]; for (size_t i = 0; i < n; i++) { sum += adc[i]; if (adc[i] < min) min = adc[i]; if (adc[i] > max) max = adc[i]; } printf(“samples=%zu sum=%u average=%u min=%u max=%u\n”, n, (unsigned)sum, (unsigned)(sum / n), min, max); uint8_t buf[8]; for (size_t i = 0; i < sizeof buf; i++) buf[i] = 0xFF; printf(“filled %zu bytes with 0x%02X\n”, sizeof buf, buf[0]); return 0; }
Output (verified by compiling and running)
samples=8 sum=16405 average=2050 min=2043 max=2060 filled 8 bytes with 0xFF
Use size_t for indexes: 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):

GCC -O2: plain loop versus volatile loop
delay_plain: ret ; the whole loop is gone delay_volatile: mov DWORD PTR [rsp-4], 0 … .L5: ; every pass really loads, adds and stores i mov eax, DWORD PTR [rsp-4] add eax, 1 mov DWORD PTR [rsp-4], eax mov eax, DWORD PTR [rsp-4] cmp eax, 999999 jbe .L5 ret

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.

MethodAccuracyCPU useUse for
Empty loopPoor, changes with compiler and clock100%Very short settling delays only
volatile counter loopPoor to fair100%Rough startup waits
SysTick polling (HAL_Delay)Good (1 ms ticks)100% while waitingSimple programs
Timer interrupt or low-power waitExcellentAlmost noneProduction code
volatile_loop.c
#include <stdio.h> int main(void) { volatile unsigned counter; unsigned total = 0; for (counter = 0; counter < 5; counter++) /* every use of counter reads or writes memory */ total += counter; printf(“total=%u counter=%u\n”, total, (unsigned)counter); return 0; }
Output (verified by compiling and running)
total=10 counter=5

9. Embedded Uses of the for Loop

JobLoopNote
Clear a bufferfor (i = 0; i < N; i++) buf[i] = 0;Or memset, usually faster
Scan ADC channels 0..15for (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..PD15for (p = 12; p <= 15; p++)Mask is 1u << p
Bitwise CRCinner loop over 8 bits per byteTable lookup is faster
Main programfor (;;) { ... }Never returns
Timeout while polling a flagfor (n = TIMEOUT; n > 0 && !(SR & RDY); n--)Always bound the wait
embedded_loops.c
#include <stdio.h> #include <stdint.h> static uint32_t GPIOD_ODR; int main(void) { /* LED chase PD12..PD15 */ for (unsigned pin = 12; pin <= 15; pin++) { GPIOD_ODR = (1u << pin); printf(“pin PD%u -> ODR=0x%04X\n”, pin, (unsigned)GPIOD_ODR); } /* Software SPI: shift out one byte, MSB first */ uint8_t data = 0xA5; printf(“bits of 0x%02X: “, data); for (int b = 7; b >= 0; b–) printf(“%d”, (data >> b) & 1); printf(“\n”); /* Polling with a timeout */ uint32_t SR = 0; /* flag never becomes ready */ unsigned n; for (n = 5; n > 0 && !(SR & 1u); n–) ; printf(“timeout %s (n=%u)\n”, n == 0 ? “expired” : “not expired”, n); return 0; }
Output (verified by compiling and running)
pin PD12 -> ODR=0x1000 pin PD13 -> ODR=0x2000 pin PD14 -> ODR=0x4000 pin PD15 -> ODR=0x8000 bits of 0xA5: 10100101 timeout expired (n=0)

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; -O3 or #pragma GCC unroll 4 can 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.
invariant.c
#include <stdio.h> #include <string.h> int main(void) { const char *s = “STM32F407 Discovery”; unsigned upper = 0; for (size_t i = 0, len = strlen(s); i < len; i++) /* strlen called once */ if (s[i] >= ‘A’ && s[i] <= ‘Z’) upper++; printf(“%u uppercase letters in \”%s\” (%zu chars)\n”, upper, s, strlen(s)); return 0; }
Output (verified by compiling and running)
5 uppercase letters in “STM32F407 Discovery” (19 chars)

11. Common Mistakes

Mistake 1 — stray semicolon after the header: 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.
Mistake 2 — <= instead of < on array bounds: Reads or writes one element past the end.
Mistake 3 — unsigned counter with >= 0: The loop never ends.
Mistake 4 — modifying the counter inside the body: Hard to follow and error-prone; use while for such loops.
Mistake 5 — floating-point counters: Accumulating 0.1 does not give exact values.
Mistake 6 — empty delay loop without volatile: The optimiser deletes it.
Mistake 7 — unbounded polling: A missing hardware flag hangs the whole program. Add a timeout.
Mistake 8 — reusing the loop variable name in a nested loop: The inner loop changes the outer counter.

12. Best Practices for the for loop in Embedded C

  • Declare the counter in the header: for (size_t i = 0; ...).
  • Use i < N with the count from sizeof.
  • 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 < n from 0 gives exactly n passes.
  • Unsigned counters need i-- > 0 or an offset, never i >= 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

What is the order of execution of a for loop?
Initialisation runs once, then the condition is tested. If true the body runs, then the update, then the condition again. When the condition is false the loop ends and the update is not run.
Why does for (unsigned i = 5; i >= 0; i–) never end?
An unsigned value is always greater than or equal to zero, so the test is always true. After 0 the decrement wraps to the largest unsigned value. Use a signed counter or the form for (i = n; i– > 0; ).
How do I write an infinite loop in embedded C?
Use for (;;) or while (1). Both are idiomatic, compile to the same code and are the structure of a bare-metal main function.
Can I declare a variable in the for header?
Yes since C99. The variable exists only inside the loop. GCC accepts it by default (gnu11).
Why is my empty delay loop not working with optimisation?
The compiler removes loops that have no side effects. Declare the counter volatile, or better, use a hardware timer.
Is counting down faster than counting up?
On ARM it can save one compare instruction per pass, but modern compilers usually make this change themselves. Choose the direction that is clearer for the algorithm.

Ready to practise?

Next: worked examples with LED chases, ADC averaging, software SPI, reversing arrays and timeouts on real output.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *