Storage Class #3: static
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Use static Variables to Keep State Between Function Calls

📑 On this page:
  • What Does static Mean?
  • Simple Rules to Remember
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What a static variable is, in plain words
  • Why a static variable keeps its value when the function ends
  • How to count how many times a function has been called
  • Why a normal (auto) variable "forgets" its value and a static one doesn't
  • Why static is safer than using a global variable for this

What Does static Mean?

Normally, when a function finishes running, every variable inside it is thrown away. The next time you call the function, the variables start fresh. That's how auto variables work.

A static variable is different. It is created once, stays alive for the whole program, and remembers its value each time the function is called again. From outside the function, you can't see it — but it's still there.

Think of it like a small notebook inside a function. Everyone who calls the function can read and write in the notebook, but only the function itself is allowed to open it. The notebook survives between visits.

💡 In one line: A static local variable keeps its value between calls — but you can only use it from inside the function that declares it.

C program using static variables to keep state between function calls

Simple Rules to Remember

Question Answer
Created when?Once, before the program starts
Destroyed when?When the program ends
Starting value?Zero, if you don't give it one
Who can see it?Only the function that declares it
Does it remember values?Yes — that's the whole point

Complete C Program

Program: A counter that remembers how many times it was called

#include <stdio.h>

/* This function remembers its count between calls */
void staticCounter(void) {
    static int count = 0;   /* created only once */
    count++;
    printf("staticCounter called %d time(s)\n", count);
}

/* This function forgets its count every time */
void autoCounter(void) {
    int count = 0;          /* reset to 0 on every call */
    count++;
    printf("autoCounter   called %d time(s)\n", count);
}

int main(void) {
    int i;

    printf("--- using static ---\n");
    for (i = 0; i < 5; i++)
        staticCounter();

    printf("\n--- using auto ---\n");
    for (i = 0; i < 3; i++)
        autoCounter();

    return 0;
}
                                    

Program Output

--- using static ---
staticCounter called 1 time(s)
staticCounter called 2 time(s)
staticCounter called 3 time(s)
staticCounter called 4 time(s)
staticCounter called 5 time(s)

--- using auto ---
autoCounter   called 1 time(s)
autoCounter   called 1 time(s)
autoCounter   called 1 time(s)
                                

Step-by-Step Explanation

Let's walk through the program slowly and see exactly what happens.

1. The function with static:

void staticCounter(void) {
    static int count = 0;
    count++;
    printf("staticCounter called %d time(s)\n", count);
}
                                

The first time staticCounter() runs, count is created and set to 0. It goes up to 1 and prints 1. When the function ends, count does not disappear. The second time the function runs, the line count = 0 is skipped — count is already there with the value 1. It goes up to 2 and prints 2. This continues: 3, 4, 5.

2. The function without static:

void autoCounter(void) {
    int count = 0;
    count++;
    printf("autoCounter   called %d time(s)\n", count);
}
                                

Here count is an ordinary variable. Every call starts it at 0, adds 1, prints 1. When the function ends, count is gone. The next call starts all over again. That's why it always prints 1.

3. Calling both from main:

for (i = 0; i < 5; i++) staticCounter();
for (i = 0; i < 3; i++) autoCounter();
                                

The first loop calls the static version five times — you see 1, 2, 3, 4, 5. The second loop calls the auto version three times — you see 1, 1, 1. Same code, different storage class — completely different behaviour.

4. Why is static better than a global here?

A global variable could do the same job, but it would be visible to every function in the file — someone else might accidentally reset it. With static, the counter belongs only to staticCounter(). Other code can't touch it. You get persistence without giving up safety.

🎯 Remember this: static gives a function a memory of its own. The value survives between calls, but nobody outside the function can see the name. If you want a counter, a cache, or a "has this already been done?" flag inside a function — static is your tool.

Frequently Asked Questions

1. When does a static variable get its starting value?

Before the program runs — not the first time the function is called. The compiler puts the initial value into the program's data and it's ready to use the moment main starts. That's why the initializer is skipped on later calls.

2. What if I don't give a static variable a starting value?

It starts at zero. The C standard guarantees this for static variables. Ordinary auto variables are different — they contain garbage until you assign a value. So static int count; is safe, but int count; is not.

3. Can I use a static variable from another function?

No. A static local can only be seen inside the function that declares it. Its name is not exported. Even if you tried to write printf("%d", count); in main, the compiler would refuse — count is not visible there.

4. Are static variables safe in multi-threaded programs?

No. If two threads call the same function at the same moment, they both read and write the same static variable. One thread might overwrite the other's value. For thread-safe state, use _Thread_local (C11) or protect the variable with a mutex.

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

A static local lives inside a function — only that function can see it. A static global is at the top of the file — every function in the file can see it, but other files cannot. Both live for the whole program. The difference is who can see the name.

💡 Tip: If a function needs to remember something from one call to the next, reach for static first — not a global. It keeps the state private and makes your code easier to reason about.

📖 Related Tutorials

  • Storage Classes in C — Full Tutorial
  • 1. auto Storage Class
  • 2. register Storage Class Performance
  • 4. extern Storage Class Across Files
  • 9. Static Unique Identifiers
  • All Storage Class Assignments

Previous Topic: -->> 2. register Storage Class Performance   ||   Next topic: -->> 4. extern Storage Class Across Files


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.