Course contentsShow
← C
Lesson 145 of 1,2192. Variables and TypesFree lesson

Persisting data between function calls

Persisting data between function calls

What you'll learn: How to use the static keyword to make a variable remember its value even after a function finishes running.

The problem with "local" memory

Imagine a waiter at a restaurant who has a notepad. Every time they walk to a new table, they tear off the page, throw it away, and start fresh. In C, standard variables inside a function work exactly like this. When the function ends, the variable is destroyed. When the function is called again, the variable starts from scratch.

Usually, this is good! We don’t want old data cluttering up new tasks. But sometimes, you need a function to have a "memory"—like a counter that tracks how many times a button has been pressed or how many customers have entered a store.

Enter the static keyword

By placing the word static before a variable declaration, you change its behavior entirely. Instead of being "thrown away" when the function ends, a static variable stays in the computer's memory for the entire duration of the program.

Think of it like a scoreboard on a wall rather than a note in a pocket. The waiter might leave the room, but when they come back, the numbers on the scoreboard are exactly where they left them.

Seeing it in action

In the code below, notice how count is initialized to 0 only once. Every subsequent time the function is called, C skips the initialization and uses the value left over from the last visit.

#include <stdio.h>

void incrementVisitorCount() {
    // This line only happens the very first time the function is called
    static int count = 0; 
    
    count++;
    printf("Visitor number: %d\n", count);
}

int main() {
    incrementVisitorCount(); // Prints: Visitor number: 1
    incrementVisitorCount(); // Prints: Visitor number: 2
    incrementVisitorCount(); // Prints: Visitor number: 3
    return 0;
}

If we had used int count = 0; without the static keyword, the output would simply be "Visitor number: 1" three times in a row, because the variable would reset to zero every time the function started.

Why use this?

Static variables are perfect for "stateful" functions. They allow you to keep data private within a single function (so other parts of your code can’t accidentally mess with it) while still allowing that function to remember its history across the lifespan of your program.

Key takeaway

Use the static keyword inside a function to create a variable that retains its value between multiple function calls.