What is Optional For Loop Expressions- Best C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course • Chapter 5 • Lecture 13

Optional For Loop Expressions

Part of our free C programming course for embedded systems: learn what happens when you leave out any part of a for loop, and why embedded C programmers do it on purpose.

Welcome to another lecture of this free C programming course from EmbeddedPathashala. The classic for loop looks rigid: initialise, test, update. In real embedded C programming, though, you will constantly see loops with empty slots, such as for (;;) or for (; n > 0; n /= 10). This free C tutorial explains exactly what each empty slot means, when it is safe, and when it hides a bug.

What You Will Learn

  • The three parts of a for statement and the exact order the compiler runs them.
  • What happens when you omit the initialisation, the condition, or the update part.
  • Why the two semicolons can never be dropped.
  • How to write a digit-counting loop that needs no initialisation and no explicit update.
  • How to build a loop that waits for a hardware condition using break.
  • Common mistakes and a few best practices for C programming for embedded systems.

Prerequisites

You should already be comfortable with variables, arithmetic operators, relational operators and the plain for loop from the previous lectures of this free embedded C course. A GCC compiler on Linux, macOS, or Windows (MinGW) is enough to run every example.

Anatomy of the For Loop

A for statement has three expressions inside the parentheses, separated by semicolons. Here they are, with the names we will use in this free C tutorial:

for (init_expr; test_expr; update_expr)
    body;
PartWhen it runsHow many times
init_exprOnce, before anything else1
test_exprBefore every iterationiterations + 1
bodyOnly if test_expr is non-zeroiterations
update_exprAfter every iteration of the bodyiterations
For Loop Execution Order
1. init_expr (once) 2. test_expr 3. body 4. update_expr back to step 2
test_expr is 0 → loop ends, control moves to the next statement

The test is evaluated one more time than the body runs, because the final failing test is what ends the loop. Keep this order in mind, because every omitted-expression variant below simply removes one box from the diagram above.

Which Parts Can You Leave Out?

All three expressions are optional. The only rule is that both separating semicolons must stay, because they tell the compiler which slot is which. Writing for (i = 0 i < 5 i++) is a syntax error, while for (;;) is perfectly legal.

FormMeaningTypical use
for (; test; update)No initialisation here, it was done earlierContinue a counter that already has a value
for (init; ; update)Condition missing, treated as always trueLoop that exits through break
for (init; test; )Update done inside the bodyStep size depends on the data
for (;;)Nothing at all, infinite loopEmbedded main loop (super loop)

Omitting the Initialisation

If the variable is already prepared, there is nothing to initialise. The first slot is left empty but the semicolon stays. This is common when the starting value comes from a function or from an earlier calculation.

Omitting the Condition

An empty test is treated by the C standard as a non-zero constant. The loop therefore never ends by itself, so something inside the body must stop it, usually break or return. Without that statement you have created an infinite loop, which we study in lecture 17 of this free embedded systems course.

Omitting the Update

If the update expression is empty, the loop variable only changes when your body changes it. That is useful when different iterations must move by different amounts, for example multiplying by 3 on every pass instead of adding 1.

Demo: Four Loops, Four Variants

The program below shows all four shapes side by side. It is our own original example, so type it in and compare the output with the table that follows.

#include <stdio.h>

int main(void)
{
    int i;

    /* all three parts present */
    for (i = 5; i >= 1; i--)
        printf("%d ", i);
    printf("<- full form\n");

    /* part 1 omitted: initialised earlier */
    int k = 10;
    for (; k < 14; k++)
        printf("%d ", k);
    printf("<- no init\n");

    /* part 3 omitted: update inside the body */
    for (int m = 1; m <= 20; )
    {
        printf("%d ", m);
        m *= 3;
    }
    printf("<- no update\n");

    /* part 2 omitted: runs until break */
    int reading = 40;
    for (;;)
    {
        reading += 15;
        printf("temp=%d ", reading);
        if (reading > 90)
            break;
    }
    printf("<- no condition\n");
    return 0;
}

Build and Run

$ gcc -std=c17 -Wall -Wextra -o variants variants.c
$ ./variants
5 4 3 2 1 <- full form
10 11 12 13 <- no init
1 3 9 <- no update
temp=55 temp=70 temp=85 temp=100 <- no condition

Reading the Output

The third loop prints 1, 3 and 9. After 9 the body makes m equal to 27, the test m <= 20 fails, and the loop ends. The last loop stops only after the temperature crosses 90, which is why 100 is printed: the check happens after the increment. Always trace such loops on paper once, the same way the compiler does.

Counting Digits with an Empty Initialiser

A very natural use of a free-form loop is peeling digits off a number. The expression n % 10 gives the last digit and n /= 10 removes it. There is nothing to initialise because n already holds the user’s number, so we leave the first slot empty.

#include <stdio.h>

int main(void)
{
    unsigned long n;
    printf("Enter a number: ");
    if (scanf("%lu", &n) != 1)
        return 1;

    int count = 0, total = 0;
    for (; n > 0; n /= 10)
    {
        total += (int)(n % 10);
        count++;
    }
    printf("digits = %d, digit sum = %d\n", count, total);
    return 0;
}
$ gcc -std=c17 -Wall -Wextra -o digits digits.c
$ ./digits
Enter a number: 48213
digits = 5, digit sum = 18
Peeling Digits From 48213
n = 48213, digit 3 n = 4821, digit 1 n = 482, digit 2 n = 48, digit 8 n = 4, digit 4 n = 0, stop

Notice that this loop destroys n. If you need the number afterwards, copy it into a second variable first, as we do in the Armstrong lecture. Also remember that a plain int overflows for large inputs, so we used unsigned long.

Free For Loops in Embedded C Programming

Firmware rarely ends. A microcontroller powers up, configures its clocks and peripherals, and then loops until the battery dies. That is why you will see for (;;) at the end of almost every main() in embedded C programming. The empty-condition form says clearly to the reader that the loop is intentional, and some static analysers prefer it over while (1).

Another embedded pattern uses the empty body, for example waiting for a status flag. Be careful here: the compiler may optimise away a read of a normal variable, so a hardware flag must be declared volatile.

volatile unsigned int *status = (volatile unsigned int *)0x40010000u;
for (; (*status & 0x01u) == 0; )
    ;   /* spin until bit 0 becomes 1 */

The address above is only an illustration, not a real device register. On real hardware you would use the address from your chip’s reference manual and add a timeout counter so the system never hangs forever.

Common Mistakes and Troubleshooting

  • Dropping a semicolon. for (;) does not compile. Both semicolons are mandatory.
  • Forgetting the exit. An empty condition without break or return never terminates.
  • Stray semicolon after the parentheses. for (i = 0; i < 3; i++); makes the body empty, and the next block runs only once.
  • Using the variable after the loop. A variable declared inside the first slot, such as for (int m = 1; ...), disappears when the loop ends.
  • Modifying the input number. The digit loop above consumes n, so keep a copy if you need it later.

Best Practices

  • Prefer the full three-part form when the loop simply counts. It is easiest to review.
  • Use an empty slot only when it genuinely says something, for example “continue from where we are”.
  • Comment every for (;;) with the condition that ends it, or state that it never ends.
  • In firmware, protect busy-wait loops with a timeout or a watchdog refresh.
  • Compile with -Wall -Wextra so the compiler warns about suspicious loops.

Summary and Key Takeaways

  • All three expressions of a for loop are optional, but both semicolons are required.
  • A missing condition is treated as true, so an exit statement is needed inside the body.
  • A missing initialiser means the variable was prepared earlier; a missing update means the body changes it.
  • for (;;) is the standard way to write the endless main loop of embedded firmware.

You now understand the flexibility of the for statement, which is a key stepping stone in any free C programming course aimed at embedded developers. In the next lecture we will use the comma operator to run several expressions inside a single slot of the loop header.

Frequently Asked Questions

Can a for loop in C have no expressions at all?

Yes. for (;;) is valid and loops forever until a break, return, or goto leaves it.

Why are the semicolons mandatory?

They separate the three slots. Without them the compiler cannot tell whether an expression is the initialiser, the test, or the update.

Is for (;;) better than while (1)?

Both compile to the same machine code. Many embedded coding standards prefer for (;;) because some tools warn about a constant condition in while (1).

What value does an empty condition have?

The C standard says an omitted controlling expression is replaced by a non-zero constant, so it is always true.

Does the update expression run when I use break?

No. A break leaves the loop immediately, so the update expression for that iteration is skipped.

Is this free C tutorial suitable for embedded beginners?

Yes. Every lecture in this free embedded C course starts from basics and adds microcontroller-oriented examples, so you can follow it without hardware.

Continue Your Free Embedded C Course

Next we combine several variables in one loop header using the comma operator. Keep learning with the complete free C programming course on EmbeddedPathashala.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →