What does "static" mean in C?

 

In C, the keyword static has multiple meanings depending on its context. Here are a few common uses of the static keyword:

  1. Static Variables: When used within a function, static can be used to create a static variable. A static variable retains its value between function calls and has a lifetime throughout the program's execution.
c
#include <stdio.h> void countCalls() { static int counter = 0; // Static variable retains its value between calls counter++; printf("Function call count: %d\n", counter); } int main() { for (int i = 0; i < 5; i++) { countCalls(); } return 0; }
  1. Static Functions: When used before the return type in a function declaration, static specifies that the function has internal linkage, meaning it is only accessible within the same translation unit (source file).
c
// In a file named file1.c static void staticFunction() { printf("This is a static function.\n"); } // In another file (file2.c) #include <stdio.h> // This function is not visible in file2.c because it's static in file1.c // staticFunction(); int main() { return 0; }
  1. Static Global Variables: When used outside of a function (at global scope), static specifies that a global variable has internal linkage. It is only accessible within the same translation unit (source file).
c
// In a file named globals.c #include <stdio.h> static int globalStaticVar = 42; // Static global variable with internal linkage // In another file (main.c) // Accessing globalStaticVar here would result in a linker error because it's not visible in main.c
  1. Static at Block Scope: When used inside a code block, static on local variables ensures that the variable retains its value between function calls, similar to a static variable, but its scope is limited to the block.
c
#include <stdio.h> void foo() { for (int i = 0; i < 3; i++) { static int localVar = 0; localVar++; printf("Local variable: %d\n", localVar); } } int main() { foo(); foo(); return 0; }

In summary, the static keyword in C can be used to create static variables with different scopes, static functions with internal linkage, and static global variables with internal linkage. Its precise meaning depends on where it is used in the code.

Comments