Skip to content
Home » How to use Static int as a Counter in C

How to use Static int as a Counter in C

Learn about C Program to use Static int as a Counter in C in the below code example.
Also refer the comments in the code snippet to get a detailed view about what’s actually happening.

C Program to use Static int as a Counter in C :

While the program is running, a static int variable is kept in memory. Whereas  when a function call in which the variable was declared ends, the variable is destroyed. Hence ,It can be used as counter irrespective of change of functions .Here is the simple example to show static int as a counter.

#include<stdio.h>

static int count=0;//declaring counter
int square(int a)
{
    a*=a;
    count++;//incrementing it whenever function is used
    return a;
}
int main()
{
    int i;
    int arr[10]={7,8,5,4,3,1,2,9,10,11};
    for(i=0;i<10;i++)
    {
        arr[i]=square(arr[i]);//calling function
    }
    for(i=0;i<10;i++)
    {
        printf("%d\t",arr[i]);
    }
    printf("\n The number of times function is used is %d",count);//returncount
}

49 64 25 16 9 1 4 81 100 121
The number of times function is used is 10

Here , static int is used as counter for the function “square” in above example. Likewise ,It can also be used as implementation in various phases

Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.