Static in C

The static keyword in C is used to maintain the persistence of a variable's value across function calls. When a variable is declared as static, it is initialized only once and retains its value between function invocations, rather than being reinitialized each time the function is called.

Static Variables

A static variable is one that has a local scope but a lifetime that extends throughout the program’s execution. It is used to preserve the value of a variable between function calls, without the need for it to be globally accessible.

Examples of Static in C

Static Variable Inside a Function

                    
#include <stdio.h>
void counter() 
{
    static int count = 0;  // Static variable
    count++;
    printf("Count: %d\n", count);
}
            
int main() 
{
    for (int i = 0; i < 5; i++) 
    {
      counter();  // Call the function multiple times
    }
            
    return 0;
}
                    
                

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Static Variable with Global Scope

                    
#include <stdio.h>
static int globalCount = 10;  // Static global variable
void showCount() 
{
   printf("Global count: %d\n", globalCount);
}
int main() 
{
    showCount();
    globalCount++;  // Modify the global static variable
    showCount();
            
    return 0;
}
                    
                

Output

Global count: 10
Global count: 11

Static Variable in Multi-file Programs

In multi-file programs, the static keyword helps to limit the scope of global variables to a single file. For example, if a static variable is declared in one file, it cannot be accessed directly in other files, which helps in encapsulation and prevents name conflicts.

To demonstrate this, create two files: file1.c and file2.c:

                    
// file1.c
#include <stdio.h>
static int secretCount = 100;  // Static global variable
void showSecretCount() 
{
   printf("Secret Count: %d\n", secretCount);
}
                    
                
                    
// file2.c
#include <stdio.h>
// Declaration of function from file1.c
extern void showSecretCount();
int main() 
{
   showSecretCount();  // This will work
   // printf("%d", secretCount);  // This will result in an error because secretCount is static in file1.c
    return 0;
}
                    
                

Output of Multi-file Program

Output

Secret Count: 100