Static Function in C

Static Function in C


Syntax:

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 snippet, the value of the local variable gets initialized again after every function call.

Unlike the local variable (x), the static variable (counter) was initialized only once and it did retain the same copy of variable throughout the execution of the program.

 

Output:

Static Variable's value:

1

Local Variable's value:

1

Static Variable's value:

2

Local Variable's value:

1