Static variables in C

Static variables in C

Basically, when static variables are declared, they create only a single copy of them, also known as class variables.

They retain the values assigned in the corresponding scopes and do not initialize the variables again in their new scopes.

  • Static variables remain in memory space during code execution.

  • The default value for static variable initialization is zero (0).

  • In C programming, a static variable must be initialized with a constant constant, otherwise it will return an error.

Syntax:

re‮f‬er to:lautturi.com
static Data_Type variable = value;

Example:

#include<stdio.h> 
void implement() 
{ int x = 0;
static int counter = 0; 
counter++; 
x++;
printf("\nStatic Variable's value:\n");
printf("%d",counter);
printf("\nLocal Variable's value:\n");
printf("%d",x);
} 

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

In the above code fragment, the value of the local variable will be initialized again after each function call.
Unlike the local variable (x), the static variable (counter) is initialized only once and does retain the same copy of the variable during program execution.

output:

Static Variable's value:
1
Local Variable's value:
1
Static Variable's value:
2
Local Variable's value:
1
Created Time:2017-08-29 10:31:31  Author:lautturi