C programming - static variable

‮igi.www‬ftidea.com

In C programming, a static variable is a type of local variable that retains its value between function calls. Unlike a regular local variable, which is destroyed and re-created each time the function is called, a static variable remains in memory for the duration of the program.

Here is an example of declaring and using a static variable:

#include <stdio.h>

void myFunction() {
  static int num = 0; // declaring and initializing a static variable

  num++; // incrementing the value of the static variable

  printf("The value of num is %d\n", num); // accessing the value of the static variable
}

int main() {
  myFunction(); // calling the function and incrementing the static variable
  myFunction(); // calling the function again and incrementing the static variable
  myFunction(); // calling the function again and incrementing the static variable
  
  return 0;
}

In this example, we declared a static variable named num inside the myFunction() function. The variable is initialized to 0 when the program starts. Each time the function is called, the value of the static variable is incremented by 1 and printed to the console. Because the variable is static, it retains its value between function calls, so the value of num continues to increment each time the function is called.

Static variables are often used to keep track of state within a function or to implement caching. They can also be used to limit the scope of a variable to a single function, while allowing the variable to retain its value between function calls.

It is important to note that static variables have function scope, which means they are only accessible within the function in which they are declared. They cannot be accessed or modified from outside the function.

In summary, a static variable in C programming is a type of local variable that retains its value between function calls. Static variables are often used to keep track of state within a function or to implement caching. They have function scope, which means they are only accessible within the function in which they are declared.