Storage Class: static — Unique ID Generation
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Static Variables for Unique IDs Across Calls

📑 On this page:
  • Why Static Variables for IDs?
  • What Makes static Special
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How a static local variable retains its value between function calls
  • How to use a static counter to generate unique sequential IDs
  • Why this pattern is thread-unsafe (and how to fix it)
  • The difference between static local and static global variables
  • Real-world use cases: logging, session IDs, auto-increment counters

Why Static Variables for IDs?

In many programs you need a simple way to generate unique identifiers: log entry numbers, order IDs, session tokens, or simply a counter that keeps incrementing no matter how many times a function is called. A plain auto local variable is recreated on every call and loses its value the moment the function returns. A static local variable, however, is created once and keeps its value for the entire life of the program.

That's the key insight: a static local variable inside a function is the cleanest way to maintain state across calls without exposing that state to the rest of the program. No global variable needed, no risk of accidental modification from other functions, and the name stays private to the function that owns it.

💡 In one line: A static local is a variable that remembers. Perfect for counters, ID generators, and one-time initializations.

C program showing static variable generating unique IDs across function calls

What Makes static Special

Property Behaviour
Storage durationStatic — lives for the whole program run
ScopeBlock scope — visible only inside the function that declares it
Initial valueAutomatically zero-initialized if not explicitly set
Initialization timingOnce, before the first call to the function
Thread safetyNot thread-safe — concurrent calls will race on the counter

Complete C Program

Program: Generate unique sequential IDs using a static counter

#include <stdio.h>

/* Returns the next unique ID every time it is called */
int next_id(void) {
    static int counter = 0;   /* created once, initialized to 0 */
    counter++;                /* remembered across calls */
    return counter;
}

/* A second, independent generator — its static counter is separate */
int next_batch_id(void) {
    static int batch = 1000;
    return batch++;
}

int main(void) {
    int i;

    printf("--- Generating 5 unique IDs ---\n");
    for (i = 0; i < 5; i++) {
        printf("next_id() = %d\n", next_id());
    }

    printf("\n--- Generating 3 batch IDs (independent counter) ---\n");
    for (i = 0; i < 3; i++) {
        printf("next_batch_id() = %d\n", next_batch_id());
    }

    printf("\n--- Calling next_id() again after other work ---\n");
    printf("next_id() = %d\n", next_id());

    return 0;
}
                                    

Program Output

--- Generating 5 unique IDs ---
next_id() = 1
next_id() = 2
next_id() = 3
next_id() = 4
next_id() = 5

--- Generating 3 batch IDs (independent counter) ---
next_batch_id() = 1000
next_batch_id() = 1001
next_batch_id() = 1002

--- Calling next_id() again after other work ---
next_id() = 6
                                

Notice that next_id() returned 6 at the end, even though other functions were called in between. The static variable counter kept its value. Meanwhile next_batch_id() maintained its own independent counter starting at 1000 — the two statics are completely separate.

Step-by-Step Explanation

Let's break down exactly what happens on every call.

1. The static variable is created once:

static int counter = 0;
                                

The static keyword tells the compiler: allocate this variable in the program's static data area, not on the stack. The = 0 initialization runs only once — before main() starts — not on every call. If you wrote static int counter; without an initializer, it would still be zero, because all static-storage variables are zero-initialized by the C standard.

2. The increment persists:

counter++;
return counter;
                                

Each call increments the same memory location. First call: 0 → 1, returns 1. Second call: 1 → 2, returns 2. And so on. This is the mechanism behind auto-increment IDs, which you'll see in databases, log files, and message queues.

3. Scope is still limited:

Despite living for the whole program, counter is not visible outside next_id(). Try to write counter = 99; in main() and you'll get a compile error. This is a huge advantage over a global variable: the state is encapsulated where it belongs.

4. Each function gets its own static:

next_batch_id() declares its own static int batch = 1000;. This is a completely separate memory location from counter. There's no collision, no sharing. Each static belongs to its enclosing function.

5. The state survives the whole program:

After the loops finish, we call next_id() once more and get 6. The value 5 was stored in the static area and stayed there. This is why static variables are ideal for: log sequence numbers, session counters, one-time setup flags, and any state you need to remember but keep private.

6. The thread-safety caveat:

If two threads call next_id() at the same time, the read-increment-write sequence can interleave, producing duplicate IDs. Fix it with a mutex (pthread_mutex_lock on POSIX, InitializeCriticalSection on Windows) or use an atomic integer (stdatomic.h in C11). For single-threaded programs — the common case in simple C exercises — the plain static counter is perfectly fine.

🎯 Remember this: A static local variable is the standard C idiom for "state that outlives its function but doesn't leak into the rest of the program." Use it whenever you need an auto-increment counter, a one-time flag, or a persistent cache — and remember to protect it with a lock if multi-threading is in play.

Frequently Asked Questions

1. Can I reset the static counter back to zero?

Not from outside the function — that's the whole point of encapsulation. If you need a reset, expose a companion function like void reset_id(void) { /* reset internal static */ }. But you can't access the static directly. If external control is required, a global variable is the more appropriate choice.

2. What's the difference between a static local and a static global?

A static local lives inside a function; its scope is limited to that function but its lifetime is the whole program. A static global (file-scope static) is visible throughout the file it's declared in, but not outside it — it's used to give a variable internal linkage. Both have static storage duration; the difference is visibility.

3. Is the initializer really run only once?

Yes. The C standard guarantees that a static local's initializer runs before main() begins (or at least before the first call to the function, depending on the exact wording), and never again. In practice, the compiler places the initialized value directly in the program's data section at load time — no runtime work at all for a constant initializer.

4. Can static locals be initialized with a non-constant expression?

In C, no — the initializer must be a constant expression. In C++, you can use non-constant initializers (they run the first time the function is called). This is a notable difference between the two languages and catches people who move code between them.

5. Do static variables work inside recursive functions?

Yes, but be careful: a static local is shared across all recursive calls of the same function. If you use one as a "depth counter," every frame sees the same value — which is often useful, but sometimes surprising. If you need a per-frame variable, use an ordinary automatic local; if you need to count total invocations across all recursion levels, use a static.

6. Can I use a static counter to generate unique IDs in a multi-threaded program?

Only if you protect it. Wrap the increment in a mutex or use C11 atomics (atomic_int and atomic_fetch_add). Without protection, two threads can read the same value before either writes, producing duplicate IDs — a classic data race. The C standard says concurrent modification of a non-atomic static is undefined behaviour.

💡 Tip: For a truly robust ID generator, combine the static counter with a time-based component (e.g., time(NULL) or clock_gettime) and a process ID, so IDs remain unique across program restarts. Just the static counter alone resets every time the program starts.

📖 Related Tutorials

  • Storage Classes in C — Full Tutorial
  • Static Storage Class — Complete Guide
  • 8. register Variables in Large Datasets
  • All Storage Class Assignments

Previous Topic: -->> 8. register Variables in Large Datasets   ||   Next topic: -->> All Storage Class Assignments


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.