What are Variable Scope in C Loops- Free Embedded Systems and C Programming Course

Need Help or More Information?

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

Control Statements | Free C Programming Course

Variable Scope in C Loops

Learn block scope, shadowing and static variables inside loops with gcc-tested embedded C examples.

Understanding variable scope in C loops is the difference between a program that works and one that quietly prints the wrong answer. Declare one extra variable with the same name inside a loop body and the compiler happily accepts it, yet your loop counter and your new variable are now two completely different boxes in memory. In this lecture of our free C programming course we explore block scope, shadowing, automatic versus static lifetime, and the value a loop counter holds after the loop ends. These ideas matter in embedded C programming, where one hidden variable inside a driver loop can cost hours of debugging. Every program here was compiled with gcc and the output is real.

What You Will Learn

  • What block scope means and how it applies to loop bodies
  • What shadowing is, why the compiler allows it, and how to make gcc warn you
  • The difference between an automatic variable and a static variable declared inside a loop
  • The value a loop counter holds after a for loop and after a while loop
  • How C99 loop declarations like for (int i = 0; ...) change scope
  • Habits that keep scope bugs out of embedded firmware

Prerequisites

You need the basics of declaring variables, the for and while loops, and the post-increment and post-decrement operators. If i-- inside a condition still feels strange, read the earlier operator lectures of this free C tutorial first, because they come before variable scope in C loops.

What Variable Scope in C Loops Really Means

Scope answers one question: in which part of the source code is this name visible? In C, every pair of curly braces creates a block, and a variable declared inside a block is visible only from its declaration to the closing brace. The loop body is a block, so anything declared there is born when the body starts and disappears when the body ends. That is called block scope.

Scope kindWhere it is declaredVisible inTypical embedded example
File scopeOutside every functionFrom the declaration to the end of the fileA global flag shared with an interrupt handler
Function scopeOnly labels (for goto)The whole functionCleanup labels in a driver
Block scopeInside { }From declaration to the closing braceLoop counters and temporaries
Prototype scopeIn a function declarationOnly inside the parenthesesParameter names in a header

Two boxes that happen to share one name

NameDeclared inVisible whereDies when
outer imain, before the loopWhole of main, except inside the inner blockmain returns
inner iLoop body blockOnly inside that loop bodyClosing brace of the body, every iteration

Shadowing: The Variable That Hides Another

When an inner block declares a name that already exists in an outer block, the inner one shadows the outer one. Inside the inner block, the name refers to the new variable; the outer variable is still alive but unreachable by that name. The program below makes this visible. The outer i controls the loop, and a second i inside the body is used by a countdown.

File: shadow.c

#include <stdio.h>

int main(void)
{
    int i;
    int hits = 0;

    for (i = 0; i < 4; i++) {
        int i = 10;            /* a NEW variable, hides the outer i */
        while (i-- > 7)
            hits++;
    }
    printf("outer i after loop = %d\n", i);
    printf("hits = %d\n", hits);
    return 0;
}

Compile with the extra -Wshadow flag. It is not part of -Wall, which is why many shadowing bugs survive code review:

$ gcc -std=c11 -Wall -Wextra -Wshadow -o shadow shadow.c
shadow.c: In function ‘main’:
shadow.c:9:13: warning: declaration of ‘i’ shadows a previous local [-Wshadow]
    9 |         int i = 10;            /* a NEW variable, hides the outer i */
      |             ^
shadow.c:5:9: note: shadowed declaration is here
    5 |     int i;
      |         ^
$ ./shadow
outer i after loop = 4
hits = 12

The warning tells you exactly what happened. Now let us explain the two lines of output by tracing the program.

One outer iteration, inner i starting at 10

Test (inner i–)Inner i beforeConditionInner i afterhits
1st1010 > 7 true91
2nd99 > 7 true82
3rd88 > 7 true73
4th77 > 7 false63 (loop ends)

Each of the four outer iterations creates a fresh inner i equal to 10 and counts exactly three hits, so the total is 4 x 3 = 12. Meanwhile the outer i was never touched by the countdown, so it advances 0, 1, 2, 3 and stops at 4. That is why the program prints outer i after loop = 4.

Notice what would have happened without the shadowing declaration: the countdown would have modified the same i that controls the for loop, the outer test would see strange values, and the loop could end early or never end. Shadowing is therefore not always a bug, but it is always a reason to stop and read carefully. This is the central lesson of variable scope in C loops: the same name does not always mean the same variable.

Warning: shadowing a loop counter with another variable of the same name is legal C. The compiler will not stop you unless you enable -Wshadow. Turn it on in your embedded build flags.

Automatic vs Static Variables Inside Loops

A normal local variable inside a loop body is automatic: it is created every time the block is entered and its previous value is gone. If you want a value to survive between iterations, or between function calls, declare it static. A static variable is created once, initialised once, and keeps its value for the whole program run, even though its name is still visible only inside the block.

File: static.c

#include <stdio.h>

int main(void)
{
    int k;

    for (k = 0; k < 3; k++) {
        int fresh = 0;             /* created again every iteration */
        static int kept = 0;       /* created once, lives for the whole program */

        fresh++;
        kept++;
        printf("round %d: fresh = %d, kept = %d\n", k, fresh, kept);
    }
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o static static.c
$ ./static
round 0: fresh = 1, kept = 1
round 1: fresh = 1, kept = 2
round 2: fresh = 1, kept = 3

The automatic fresh restarts from 0 every round and therefore always prints 1, while kept counts 1, 2, 3. Embedded programmers use this pattern for call counters, debounce counters and one-time initialisation flags inside driver functions. The trade-off is that static state makes a function non-reentrant, so be careful when the same code can run from both main code and an interrupt handler.

PropertyAutomatic variableStatic variable
CreatedEach time the block is enteredOnce, before main starts
Initial value if not setIndeterminate garbageZero
Lives inStack or a registerData or BSS section
Value kept between iterationsNoYes
Safe from two contexts at onceYes, each call has its own copyNo, one copy is shared

Loop Counter Values and Variable Scope in C Loops

Another scope-related question that appears constantly in exams: what is the loop counter after the loop finishes? The answer is that it holds the first value that made the test fail, as long as the counter was declared outside the loop. The demo compares a for loop with a while loop that updates the counter first.

File: finali.c

#include <stdio.h>

int main(void)
{
    int i, for_sum = 0, while_sum = 0;

    for (i = 1; i < 5; i++)
        for_sum += i;
    printf("after for   : i = %d, sum = %d\n", i, for_sum);

    i = 1;
    while (i < 5) {
        i++;                   /* update BEFORE using the value */
        while_sum += i;
    }
    printf("after while : i = %d, sum = %d\n", i, while_sum);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o finali finali.c
$ ./finali
after for   : i = 5, sum = 10
after while : i = 5, sum = 14

Why both loops end with i = 5 but different sums

LoopValues added to the sumTotal
for (i = 1; i < 5; i++) sum += i1, 2, 3, 410
while loop with i++ first, then sum += i2, 3, 4, 514

Both loops stop when i reaches 5, because 5 is not less than 5. The for loop adds the value before incrementing, so it adds 1 to 4. The while loop increments first and then adds, so it adds 2 to 5. The final counter is identical, but the sums differ, and this is the exact kind of off-by-one subtlety interviewers love.

C99 Loop Declarations and Scope in C Loops

Since C99 you can declare the counter inside the for header: for (int i = 0; i < n; i++). That counter exists only for the loop and is not visible afterwards, which removes the whole “value after the loop” question. Modern toolchains accept it with -std=c99 or later, and I recommend it for new code. Some very old embedded compilers still use C89, where declarations must be at the top of a block, so check your toolchain.

One more difference worth knowing: in C you may declare a variable with the same name as the loop counter inside the loop body, and gcc accepts it. In C++ the same code is an error, because the header variable and the body share one scope there. If you move code between C and C++ files in the same project, this is a classic surprise.

Common Mistakes and Troubleshooting

SymptomCauseFix
Outer counter never changesA same-named variable in the body shadows itRename the inner variable and compile with -Wshadow
Counter resets each iterationVariable declared and initialised inside the bodyMove the declaration outside or make it static
Loop counter unknown after loopCounter declared in the for header (C99)Declare it before the loop if you need its final value
Value is garbage on first useAutomatic variable never initialisedAlways initialise at the declaration
Static counter misbehaves with interruptsOne shared copy used from two contextsProtect with a critical section or avoid static state

Best Practices for Variable Scope in C Loops

  • Declare variables in the smallest scope that works. It keeps their meaning obvious and limits damage if you misuse them.
  • Never reuse a name in a nested block. Use distinct names such as row and col instead of two variables called i.
  • Enable -Wshadow alongside -Wall -Wextra in every embedded makefile.
  • Initialise at declaration. An uninitialised automatic variable holds garbage, and reading it is undefined behaviour.
  • Performance: block scope has no runtime cost. Compilers can reuse the same stack slot or register for variables in different blocks, so small scopes can even save RAM on a microcontroller.
  • Safety: avoid static locals in code reachable from interrupt handlers unless you protect them, since they create hidden shared state.

Summary and Key Takeaways

  • Variable scope in C loops follows block rules: a loop body is a block, and variables declared in it live only for one iteration.
  • A same-named inner variable shadows the outer one; gcc warns only with -Wshadow.
  • Static locals keep their value between iterations, automatic locals do not.
  • After a loop the counter holds the first value that failed the test, if declared outside.
  • Declare in the smallest scope, use unique names and initialise everything, the habit that makes variable scope in C loops easy to reason about.

Conclusion

Variable scope in C loops is a small topic with large consequences. A single shadowed variable can change how many times a loop runs, and a misplaced declaration can reset a counter you wanted to keep. Now that you can trace both the outer and inner variable by hand, you are ready for the next lecture, where we look at the most common loop mistakes that cause infinite loops and wrong totals. Keep following this free embedded C course in order and practise every trace table on paper before compiling.

Frequently Asked Questions

What is variable scope in C loops?

It is the region of code where a variable declared in or around a loop is visible. A variable declared inside the loop body exists only for that body and is created fresh on every iteration.

What is variable shadowing in C?

Shadowing happens when an inner block declares a variable with the same name as one in an outer block. The inner name hides the outer one until the inner block ends.

How do I make gcc warn about shadowed variables?

Add the -Wshadow flag, for example gcc -Wall -Wextra -Wshadow. It is not enabled by -Wall.

Does a variable declared inside a for loop body keep its value?

No, an automatic variable is recreated each iteration. Declare it static or move it outside the loop to keep the value.

What is the value of the loop counter after a for loop?

If the counter was declared before the loop, it equals the first value that made the test false. With for (i = 1; i < 5; i++) it is 5.

Can I declare the counter inside the for statement in C?

Yes, from C99 onwards, for example for (int i = 0; i < n; i++). The counter is not visible after the loop. Older C89 compilers do not allow it.

Why does C allow redeclaring the loop variable inside the body but C++ does not?

In C the body is a nested block with its own scope, so a new declaration is legal. In C++ the header variable and the body share one scope, so redeclaring it is an error.

Are static variables inside loops safe in embedded systems?

They are fine in single-context code, but one shared copy can be corrupted if both main code and an interrupt handler use the function. Protect it or avoid static state there.

Keep Going With the Free C Course

This free C tutorial gives students solid embedded C programming foundations. Continue to the next lecture and learn the loop mistakes that cause infinite loops.

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 *