What are Static Variables and Recursion- C Programming Course in Telugu

🚀 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 →

Static Variables and Recursion

Chapter 6, Functions: how static variables in C remember values between calls, and how recursion builds and unwinds the call stack. Part of the free C programming course on EmbeddedPathashala.

4
Runnable programs
2
Core ideas
100%
Free embedded C course

Every firmware engineer meets static variables in C within the first week of reading real code: a counter inside an interrupt handler, a “previous sample” inside a filter, a flag that must survive between two calls. This lecture of our free C programming course explains exactly how static variables in C behave, why they differ from ordinary locals, and how the same storage rules interact with recursion, the technique where a function calls itself. By the end you will be able to predict the output of the classic exam-style programs that mix a static local with a recursive helper.

The material follows the exercise pages at the end of the Functions chapter, but every program, name and explanation here is written fresh for embedded C programming students who want to learn by running code, not by memorising answers.

What You Will Learn

  • The difference between automatic, static and global storage, and when each is created and destroyed.
  • Why a static local variable is initialised only once, even if its line sits inside a function called thousands of times.
  • How to use static variables in C to build a debouncer, a call counter and similar firmware helpers.
  • The two parts every recursive function needs: a base case and a recursive case.
  • How to trace a recursive call on paper, frame by frame, and cross-check the answer with a formula.
  • Why recursion deserves caution on small microcontrollers with limited stack.

Prerequisites

You should be comfortable with defining and calling functions, passing arguments by value, and the return statement. These ideas were covered in the earlier lectures of this chapter. A working compiler such as GCC is enough to run everything below. If you are following this free embedded C course on a board, any toolchain that supports C99 will do.

Static Variables in C: Storage That Outlives a Call

A normal local variable, called an automatic variable, is created when the function starts and disappears when it returns. Its memory typically lives in the stack frame of that call, so the next call receives a brand-new, uninitialised copy. A static variable in C declared inside a function behaves differently in one important way: its lifetime is the whole program, while its visibility is still limited to the function body. Think of it as a private global variable that only one function can touch.

Scope and lifetime are different ideas

Beginners often merge two questions into one. Scope asks, “from which lines of code can I name this variable?” Lifetime asks, “for how long does the memory exist?” A static local has block scope but static lifetime. The table compares the three storage choices you will meet most often.

KindWhere declaredLifetimeDefault valueVisible to
Automatic localInside a functionOne callGarbageThat function only
Static localInside a function with staticWhole programZeroThat function only
GlobalOutside every functionWhole programZeroWhole file or project

Where each kind of variable lives in memory

Stackautomatic locals, parameters, return addressesgrows and shrinks with every call
Data segmentstatics and globals with a non-zero initial valuecopied from flash at start-up
BSS segmentstatics and globals that start at zerocleared by start-up code

A side-by-side experiment

The program below keeps two nearly identical helpers. One declares total with static, the other does not. Both are called three times with the same argument.

#include <stdio.h>

int step_counter(int step)
{
    static int total = 2;   /* created once, keeps its value between calls */
    total = total + step;
    return total;
}

int plain_counter(int step)
{
    int total = 2;          /* created afresh on every call */
    total = total + step;
    return total;
}

int main(void)
{
    for (int call = 1; call <= 3; call++) {
        int s = step_counter(8);
        int a = plain_counter(8);
        printf("call %d  static: %2d  automatic: %2d\n", call, s, a);
    }
    return 0;
}

Running it shows the difference immediately.

call 1  static: 10  automatic: 10
call 2  static: 18  automatic: 10
call 3  static: 26  automatic: 10

The automatic version restarts from 2 every time, so it can only ever answer 10. The static version executes the line static int total = 2; exactly once, before main begins, and afterwards the assignment is simply skipped. Each call therefore continues from wherever the last call stopped: 2 + 8 = 10, then 10 + 8 = 18, then 18 + 8 = 26.

Static total across three calls

1

First call

total starts at 2, adds 8, returns 10 and keeps 10.

2

Second call

The initialiser is skipped. 10 plus 8 gives 18, kept for later.

3

Third call

18 plus 8 gives 26. The automatic twin still answers 10.

Exam trap: the initialiser of a static local must be a constant expression. Writing static int total = read_sensor(); is a compile-time error in C, because the value has to exist before the program runs.

Static Variables in C for Embedded Firmware

Embedded programs are full of functions that must remember something. An interrupt service routine may count events, a filter keeps the previous sample, and a state machine tracks which state it is in. Putting that memory in a static local keeps it hidden from the rest of the project, which is far safer than a loose global.

Example: a three-sample button debouncer

Mechanical switches bounce. A common fix is to accept a new level only after it has been seen several times in a row. The function below stores the last level and a run length in two static variables.

#include <stdio.h>

/* Returns 1 only after the input level has stayed the same for 3 samples. */
int button_stable(int level)
{
    static int last = 0;
    static int same_count = 0;

    if (level == last) {
        if (same_count < 3)
            same_count++;
    } else {
        last = level;
        same_count = 1;
    }
    return same_count >= 3;
}

int main(void)
{
    int samples[] = {0, 1, 1, 0, 1, 1, 1, 1, 0};
    int n = (int)(sizeof samples / sizeof samples[0]);

    for (int i = 0; i < n; i++)
        printf("sample %d  level %d  stable %d\n",
               i, samples[i], button_stable(samples[i]));
    return 0;
}
sample 0  level 0  stable 0
sample 1  level 1  stable 0
sample 2  level 1  stable 0
sample 3  level 0  stable 0
sample 4  level 1  stable 0
sample 5  level 1  stable 0
sample 6  level 1  stable 1
sample 7  level 1  stable 1
sample 8  level 0  stable 0

Notice what the output teaches. The level flips at sample 1, but stable stays 0 until sample 6, because only then has level 1 been seen three samples in a row. The brief 0 at sample 3 resets the run length. The caller needs no extra variables, and no other function can corrupt the counters.

Static variables and interrupts

A function that keeps state in statics is not re-entrant. If it can be called from both the main loop and an interrupt, or from two RTOS tasks, the two callers will fight over one copy. For shared data, mark the object volatile when an interrupt modifies it, and protect multi-step updates with a critical section. For a single owner such as the debouncer above, a static is perfect.

Use caseWhy static fitsWatch out for
Call or error counterSurvives between calls, hidden from othersOverflow of small integer types
Previous sample in a filterNeeds history without a globalNot usable by two sensors at once
One-time initialisation flagRun set-up on first call onlyRace if two tasks call first
Lookup tableStored once, not rebuilt on the stackMark it const so it stays in flash

Static Variables in C and Recursion: The Call Stack

Now combine the storage rules with recursion. A recursive function solves a problem by reducing it to a smaller copy of the same problem. It needs two ingredients: a base case that answers the smallest version directly, and a recursive case that moves toward the base case. Forget either one and the function never finishes.

#include <stdio.h>

int sum_to(int n)
{
    if (n == 0)
        return 0;               /* base case */
    return n + sum_to(n - 1);   /* recursive case */
}

int main(void)
{
    printf("1+2+...+8 = %d\n", sum_to(8));
    return 0;
}
1+2+...+8 = 36

Because every call receives its own automatic n, the calls do not disturb each other. That is precisely the property a static variable lacks, which is why mixing a static local with recursion needs care: all the frames share one copy of the static.

Watching the frames appear and vanish

A trace makes the invisible stack visible. This version prints a line when each frame is entered and another when it returns, indenting by depth.

#include <stdio.h>

int sum_to(int n, int depth)
{
    int result;

    printf("%*senter sum_to(%d)\n", depth * 2, "", n);
    if (n == 0)
        result = 0;
    else
        result = n + sum_to(n - 1, depth + 1);
    printf("%*sleave sum_to(%d) = %d\n", depth * 2, "", n, result);
    return result;
}

int main(void)
{
    int total = sum_to(4, 0);
    printf("total = %d\n", total);
    return 0;
}
enter sum_to(4)
  enter sum_to(3)
    enter sum_to(2)
      enter sum_to(1)
        enter sum_to(0)
        leave sum_to(0) = 0
      leave sum_to(1) = 1
    leave sum_to(2) = 3
  leave sum_to(3) = 6
leave sum_to(4) = 10
total = 10

Call stack for sum_to(4), deepest frame on top

sum_to(0)returns 0 immediately: base case
sum_to(1)waiting to compute 1 + 0
sum_to(2)waiting to compute 2 + 1
sum_to(3)waiting to compute 3 + 3
sum_to(4)waiting to compute 4 + 6, gives 10

The “enter” lines go down the screen as the stack grows. The “leave” lines come back up as each frame finally receives the answer from the frame above it. No addition happens on the way down; all of the arithmetic happens on the way back.

Cross-checking with a formula

When an exercise asks for the output of a recursive series, do not trust a single trace. Check it against mathematics. The sum of 1 through n equals n times (n + 1) divided by 2. For n = 8 that is 8 times 9 divided by 2, which is 36, matching the program. If your hand trace and the formula disagree, one of them has an off-by-one mistake.

Real-World Use Cases

  • Call counters and diagnostics: a static counter records how many times a driver function reported an error, without exposing a global.
  • Signal filters: moving averages and low-pass filters keep their previous output in a static.
  • Tree and list walks: directory traversal and expression parsers are naturally recursive on a host PC, even if firmware prefers loops.
  • Divide and conquer: binary search, quicksort and merge sort express their logic most clearly as recursion.

Common Mistakes and Troubleshooting

SymptomLikely causeFix
Counter restarts every callThe static keyword is missingDeclare the variable static
Compiler rejects a static initialiserIt calls a function or reads a variableUse a constant, set the value inside the function
Recursive function never endsNo base case, or the argument moves away from itCheck that every recursive call is closer to the base case
Random crash after deep recursionStack overflowLimit the depth or switch to a loop
Wrong total by exactly one termBase case returns 1 when it should return 0Trace the smallest input by hand

Best Practices, Performance and Security

Best practices

  • Prefer a static local over a global when only one function needs the memory.
  • Give recursive functions an explicit base case at the top, before any other logic.
  • Use const on static tables so the linker can place them in flash.
  • Document any function that keeps hidden state, because it is not re-entrant.

Performance: reading a static is as cheap as reading a global, and it avoids re-creating a lookup table on every call. Each recursive call, however, pushes a frame holding a return address, saved registers and locals, then pops it again. A loop usually runs faster and uses constant stack.

Security and safety: unbounded recursion fed by external input, such as a nested packet format, lets an attacker exhaust the stack. Safety standards such as MISRA C:2012 forbid recursion in Rule 17.2 for exactly this reason, so production firmware often converts it to iteration. Static state in shared code can also leak data between users of a function, so clear it when a session ends.

Key Takeaways and Conclusion

  • A static local is initialised once, keeps its value between calls and is visible only inside its function.
  • Automatic locals are fresh on each call; that is why recursive frames never interfere with each other.
  • Every recursive function needs a base case and a step that moves toward it.
  • Arithmetic in a simple recursive sum happens while the stack unwinds, not while it grows.
  • Check hand traces against a formula to catch off-by-one mistakes.

Static variables in C and recursion look like separate topics, yet both come down to one question: where does a value live, and for how long? Once you can answer that for every variable in a program, output-prediction questions become mechanical. Next, we compare iteration and recursion on the same problems and see when each one wins in embedded C programming.

Frequently Asked Questions

What is the difference between a static variable and a global variable in C?

Both live for the whole program and start at zero. A global can be named from any function in the file, while a static local can be named only inside the function that declares it.

When is a static local variable initialised?

Before the program starts running, not when the function is first called. The initialiser must therefore be a constant expression.

Are static variables in C stored on the stack?

No. They live in the data or BSS segment, which is allocated once and never freed, so they do not grow or shrink with function calls.

Can a recursive function use a static variable?

Yes, but every recursive frame shares the single static copy. That is useful for counting calls and dangerous if you expected each frame to have its own value.

Is recursion allowed in embedded C programming?

Technically yes, but many projects forbid it because stack space is small and worst-case depth is hard to prove. Loops are the usual replacement.

Why does my recursive sum print the wrong total?

Check the base case first. Returning 1 instead of 0 for an empty range adds an extra term to every result.

Keep Going With the Free C Programming Course

Continue through Chapter 6 for iteration versus recursion, output tracing and exercise solutions. Every lecture is free, with runnable code you can test on your own machine.

💬 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 →