Static Keyword

In C programming, the 'static' keyword is used to declare variables, functions, or data members that have a static storage duration.

Variables declared as static are initialized only once and retain their values across multiple function calls.

Here's an example of using the 'static' keyword to declare a static variable:


 #include <stdio.h> 

void count() {
  static int counter = 0;
  counter++;
  printf("Counter: %d\n", counter);
}

int main() {
  count(); // Counter: 1
  count(); // Counter: 2
  count(); // Counter: 3
  return 0;
}

    

In this example, the 'static' keyword is used to declare a static variable named 'counter' inside the function 'count()'.

The variable is initialized only once, and its value is retained across multiple function calls.

Each time the 'count()' function is called, the 'counter' variable is incremented, and its value is printed using 'printf'.

The 'static' keyword can also be used to declare static functions and static data members within a structure.

When used with functions, the 'static' keyword restricts the visibility of the function to the current file, making it private to that file.

The 'static' keyword has different meanings depending on its context, but in the case of variables, it allows for the preservation of their values across function calls and restricts their scope to the current block or file.

Loading...

Search