Static

The static keyword in C is used to control the visibility and lifetime of variables and functions. It can be applied to both variables and functions.

Usage of Static Keyword

1. Static Global Variable

2. Static Function

3. Static Local Variable

4. Static Member Variables (in C++)

5. Static Method (in C++)

1. Static Global Variable

A static global variable is declared at the top of the program with the static keyword.

It is accessible only within the file where it is declared.

Example:

#include <stdio.h>

static int count = 0; // Static global variable

void increment() {
    count++;
    printf("Count: %d\n", count);
}

int main() {
    increment();
    increment();
    return 0;
}

Output:

Count: 1
Count: 2

2. Static Function

A static function is a function declared with the static keyword.

It is only accessible within the file it is declared in.

Example:

#include <stdio.h>

static void displayMessage() { // Static function
    printf("Hello, static function!\n");
}

int main() {
    displayMessage();
    return 0;
}

Output:

Hello, static function!

3. Static Local Variable

A static local variable is declared inside a function with the static keyword.

Its value persists between function calls.

Example:

#include <stdio.h>

void counter() {
    static int count = 0; // Static local variable
    count++;
    printf("Count: %d\n", count);
}

int main() {
    counter();
    counter();
    counter();
    return 0;
}

Output:

Count: 1
Count: 2
Count: 3

Properties of Static Variables

1. Memory Allocation:

The memory for a static variable is allocated once and remains allocated throughout the program's lifetime.

2. Initialization:

If not explicitly initialized, static variables are automatically initialized to zero.

3. Scope:

The scope of a static local variable is limited to the function in which it is declared.

The scope of a static global variable or function is limited to the file in which it is declared.

4. Persistence:

Static local variables retain their value between function calls.

Differences Between Static and Global Variables

• Global Variables:

Declared outside any function.

Accessible throughout the program.

Can be accessed by other source files if declared with extern.

• Static Variables:

Declared with the static keyword.

Static global variables are only accessible within the file they are declared in.

Static local variables persist their value between function calls but are only accessible within the function they are declared in.