Back to course

Introduction to Static Variables and Functions

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 58: Introduction to Static Variables and Functions

The static keyword has different meanings depending on whether it is applied inside a function, to a global variable, or to a function.

1. Static Local Variables (Lifetime Extension)

When a local variable is declared static, its scope remains local to the function, but its lifetime is extended to the entire duration of the program. It retains its value between function calls.

c void count_calls() { static int call_count = 0; // Initialized only ONCE call_count++; printf("Function called %d times.\n", call_count); }

int main() { count_calls(); // 1 count_calls(); // 2 return 0; }

2. Static Global Variables (Limiting Visibility)

When a global variable is declared static, its visibility (linkage) is limited to the file in which it is defined. It cannot be accessed by other files using the extern keyword.

  • Benefit: Prevents name clashes and enforces encapsulation within a module.

3. Static Functions (Limiting Visibility)

When a function is declared static, it can only be called from within the same source file where it is defined. This creates 'private' helper functions for a module.

c // utility.c static void internal_logger(char *msg) { ... } // Cannot be called from main.c

void public_function() { internal_logger("Called public function"); // OK }