0Pricing
C Academy · Lesson

static Variables

Persistent locals.

The static Keyword

A static local variable keeps its value between calls to the function. Its lifetime is the whole program.

#include <stdio.h>
void f(void) {
    static int count = 0;
    count++;
    printf("count = %d\n", count);
}
int main(void) {
    f();
    f();
    f();
    return 0;
}

Initialized Once

A static variable is initialized only the first time the function runs. Later calls skip the initializer.

#include <stdio.h>
void f(void) {
    static int x = 100;
    printf("x = %d\n", x);
    x += 10;
}
int main(void) {
    f();
    f();
    return 0;
}

All lessons in this course

  1. auto and Local Scope
  2. static Variables
  3. extern and Global
  4. register and const
← Back to C Academy