What are Static Variables in C- Embedded C Programming Course Online

Need Help or More Information?

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

Static Variables in C

Chapter 6, Lecture 31 of our free C programming course: master static variables in C, the variables that remember their value between function calls, with examples from embedded C programming.

Welcome to the next lecture of our free C programming course on EmbeddedPathashala. In this free C tutorial we study static variables in C. A static variable keeps its value from one function call to the next, yet it stays hidden inside the function that owns it. That makes it the perfect tool for counters, state machines, debounce timers and ID generators in embedded C programming. After this lecture you will know exactly when to reach for static instead of a local or a global variable. Static variables in C are small in syntax but large in consequence, so we look at how they behave, where they are stored and how they can surprise you.

What You Will Learn

  • The syntax for declaring a static variable inside a function
  • Why the initialisation happens only once
  • How a static variable differs from a local and from a global
  • The default value of an uninitialised static variable
  • The second meaning of static at file level
  • Embedded use cases and the risks of hidden state

Prerequisites

Complete the two previous lectures on local and global variables. You need to understand scope (who can see a name) and lifetime (how long the memory exists), because static variables combine the scope of a local with the lifetime of a global.

What Is a Static Variable in C?

You create a static variable by placing the keyword static in front of an ordinary declaration:

static type variable_name = initial_value;

Declared inside a function, such a variable has local scope but program lifetime. Only that function can use the name, but the storage exists from program start to program end. Two rules define its behaviour:

  • The initialisation is performed once, not on every call. It is in fact done before the program starts, by the compiler and the startup code.
  • If you give no initial value, the variable starts at zero, just like a global.

Because the value is kept between calls, the function gains a private memory. This is often described as giving a function “state”.

Three kinds of variables compared by scope and lifetime

Local

Visible: one block Lives: one call

Static local

Visible: one function Lives: whole program

Global

Visible: whole file onward Lives: whole program

Static Variables in C: A Working Example

The function below contains one static variable and one ordinary local variable, both modified on every call. Save the program as ep_static.c.

#include <stdio.h>

static int next_id(void)
{
    static int id = 100;   /* initialised once */
    int calls = 0;         /* fresh each call */
    calls++;
    id++;
    printf("calls=%d id=%d\n", calls, id);
    return id;
}

static int uninit_static(void)
{
    static int hits;       /* zero by default */
    return ++hits;
}

int main(void)
{
    next_id();
    next_id();
    next_id();
    int a = uninit_static();
    int b = uninit_static();
    int c = uninit_static();
    printf("hits: %d %d %d\n", a, b, c);
    return 0;
}
gcc -Wall -Wextra -o ep_static ep_static.c
./ep_static

calls=1 id=101
calls=1 id=102
calls=1 id=103
hits: 1 2 3

Why Static Variables in C Behave This Way

Look at the output. The ordinary local calls prints 1 every time, because it is recreated and reset to 0 on each call. The static variable id goes 101, 102, 103. Its line static int id = 100; is not executed as a runtime assignment. The value 100 is placed in memory before main runs, and later calls simply skip the initialisation. That is why the third call sees 102 and increments it to 103.

The second function proves the default rule. The variable hits has no initialiser, yet the three calls return 1, 2 and 3, so it must have started at zero. We stored the three results in separate variables before printing them. Calling the function three times inside a single printf would work too, but the order in which the arguments are evaluated is not specified by the C standard, so the numbers might print in a different order.

Remember: A static initialiser must be a constant expression. You cannot write static int x = read_sensor(); because the value is fixed at build time, not at run time.

Where Static Variables in C Live in Memory

Static and global variables are stored in fixed locations in RAM, never on the stack. The linker places them into one of two regions.

RegionHoldsStartup action
.dataStatic and global variables with a non-zero initial valueInitial values copied from flash to RAM
.bssStatic and global variables with no initial value or zeroRegion cleared to zero
StackOrdinary local variablesCreated on each function call

This has a practical consequence for embedded engineers. Every static variable permanently uses RAM, even when its function is rarely called. On a device with 8 KB of RAM, a large static buffer is a decision that deserves thought.

The Other Meaning of static: File Scope

The keyword has a second job at file level. A global variable or a function declared with static at the top of a source file becomes private to that file, which the standard calls internal linkage. Other files cannot link to it, even if they declare it with extern. You have seen this throughout the course: every helper function in our demos is declared static, which keeps names from clashing and lets the compiler optimise more freely.

Where static appearsEffect
Inside a function, on a variableValue is kept between calls, name is local
At file level, on a variableVariable is private to the file
At file level, on a functionFunction is private to the file

Rule of thumb: reach for a static local variable when a function needs a private memory that outlives a single call, such as a counter or a previous-reading store. If two functions need that memory, a file-level static variable is the better choice, because it stays hidden from other files while being shared inside the file.

Real-World Uses in Embedded C Programming

  • Call counters: counting how many times a handler ran, for statistics or rate limiting.
  • State machines: a static int state remembers where a protocol parser stopped between bytes.
  • Debouncing: remembering the previous button reading to detect a change.
  • ID or sequence generators: like the next_id function above, handing out unique numbers.
  • Large buffers: a static array keeps a big work area off the small stack.
  • One-time set-up: a static int initialised flag lets a function prepare hardware only on the first call.

Common Mistakes with Static Variables

Expecting the initialiser to run each call. If you want a variable reset every time, do not make it static, or assign it explicitly on a separate line.

Thread and interrupt safety. A function with static state is not re-entrant. If both the main loop and an interrupt call it, the two callers share and corrupt the same variable. Use locals, or protect the access.

Hidden state hurts testing. A function that behaves differently on its second call is harder to unit test. Reset hooks or passing state explicitly makes testing easier.

Forgetting RAM cost. Ten functions each with a 200 byte static buffer quietly consume 2 KB.

Best Practices, Performance and Security

  • Choose static locals over globals when only one function needs the remembered value. Well-chosen static variables in C keep the rest of the program free of shared state.
  • Comment every static variable with what it remembers and why.
  • Avoid static state in functions that can be called from interrupts unless access is protected.
  • Use static const for lookup tables so they sit in flash rather than RAM.
  • Add static to every helper function and file-level variable that is not part of the public interface.
  • Static buffers that held secrets should be cleared after use, because they stay in memory for the whole run.

Summary and Key Takeaways

  • A static variable in C is declared with the static keyword and keeps its value between calls.
  • Its initialisation happens once, and uninitialised static variables start at zero.
  • It combines the narrow scope of a local with the long lifetime of a global.
  • Static variables live in .data or .bss, not on the stack.
  • At file level, static makes a variable or function private to that file.

Conclusion

You now understand how static variables in C work, and you have the complete picture of C storage for variables: locals are short-lived and private, globals are long-lived and shared, and static variables sit in between, long-lived but private. Picking the right one is a design skill that separates tidy firmware from tangled firmware. In the next lecture we use all of this knowledge to understand recursion, where a function calls itself and every call gets its own set of local variables.

Frequently Asked Questions

What is a static variable in C?

A variable declared with the static keyword. Inside a function it keeps its value between calls but is visible only to that function.

How many times is a static variable initialised?

Only once, before the program starts running. Later calls skip the initialisation.

What is the default value of a static variable?

Zero, for all arithmetic types. Pointers default to null.

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

Both live for the whole program, but a static local variable can be used only inside its own function, while a global is visible to many functions.

Where is a static variable stored?

In the .data section if it has a non-zero initial value, otherwise in .bss. Neither is on the stack.

Is a function with static variables safe to call from an interrupt?

Not unless access is protected, because the static state is shared by every caller and the function is no longer re-entrant.

Keep Going With the Free Embedded C Course

Continue to the next lecture on recursion, share this free C tutorial with a friend, and keep building your embedded C programming skills.

Need Help or More Information?

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

1 Comment

Leave a Reply

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