← Back to C Course | Chapter 14: Additional Topics | Lesson 4 of 9

C Static Functions & Variables

Static Local Variables

A static local variable is initialized only the first time its declaration is reached and then keeps its value between successive calls to the function, unlike an ordinary local variable which is recreated from scratch (and loses its previous value) every time the function runs.

Example: Static Local Variables

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

Static Global Variables

A static global variable is visible only within the source file where it's declared, meaning other .c files in the same project cannot access or accidentally modify it even if they declare a variable with the exact same name — the static keyword gives it file-level (internal) linkage instead of program-wide linkage.

Example: Static Global Variables

c
#include <stdio.h>
static int fileScoped = 42;
int main() {
	printf("%d", fileScoped);
	return 0;
}

Static Functions

Declaring a function static restricts its visibility to the file it's defined in, which is useful for internal helper functions that other files have no legitimate reason to call directly, keeping your project's externally usable API smaller and more intentional.

Example: Static Functions

c
#include <stdio.h>
static int helper(int n) {
	return n * 2;
}
int main() {
	printf("%d", helper(5));
	return 0;
}

Scope Isolation with Static

Because static functions and static global variables are invisible outside their own file, two different .c files in the same project can safely declare a static function or variable with an identical name without the linker ever reporting a naming conflict between them.

Example: Scope Isolation with Static

c
#include <stdio.h>
static int value = 10;
int main() {
	printf("%d", value);
	return 0;
}

Memory Lifetime of Static Variables

Static variables live in the program's data segment rather than on the stack, meaning they are allocated exactly once when the program starts and continue occupying that memory for the program's entire runtime, regardless of how many times the function containing them is called.

Example: Memory Lifetime of Static Variables

c
#include <stdio.h>
void increment() {
	static int total = 0;
	total++;
	printf("%d ", total);
}
int main() {
	increment();
	increment();
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.