CodeBlanks Logo Icon CodeBlanks

static

  • C course
  • Intermediate
  • Lesson 61/116
  • 5 min

Learn file-local variables and functions with static.

The static keyword

static has two meanings. At file scope (outside functions), it makes a variable or function file-local; another .c file can't see it even with extern. Inside a function, it extends the variable's lifetime to the whole program but keeps scope the same.

Example: static int internal_counter = 0; in one .c file is visible only there. This hides a module's implementation detail; the header exposes only the public API, internal helpers are static. This technique is called internal linkage.

static inside a function

Inside a function, static int calls = 0; makes calls keep its value across calls. On the first call it's initialized to zero; later calls keep the previous value. A normal local would reinitialize each call.

Example: int next_id(void) { static int id = 0; return ++id; }. Each call returns one more than before. This pattern fits counters and caches. It's not thread-safe though; use carefully in multi-threaded programs. The lifetime is the whole program, but scope stays inside the function; not accessible from outside.

Practice Write a static counter

Write int next_id(void) with static int id = 0; and return ++id; inside. In int main(void) add printf("%d \n", next_id()); and printf("%d\n", next_id());. Don't forget <stdio.h>.

Starter code

main.c
#include <stdio.h>

// next_id: persistent counter and increment

int main(void) {
    // Call next_id twice and print
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int next_id(void) {
    static int id = 0;
    return ++id;
}

int main(void) {
    printf("%d \n", next_id());
    printf("%d\n", next_id());
    return 0;
}

Expected output

1 
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match static usages

Term Meaning
File-scope static Internal linkage
Function-scope static Persistent lifetime
extern Cross-file sharing
Header Public API

2 Complete the counter function

Question
int next_id(void) {
    ____ int id = 0;
    return ++id;
}
Answer
int next_id(void) {
    static int id = 0;
    return ++id;
}

Explanation: static int id = 0; preserves the value across calls.

3 What does a file-scope static variable do?

  • Becomes visible from other files
  • Stays visible only in its file Correct answer
  • Auto-resets
  • Gives program-long lifetime

Explanation: File-scope static gives internal linkage.

All lessons in Intermediate