Software & Finance





C Programming (Turbo C++ Compiler) - Static Variables For Counting Function Calls





Variables can be declared in stack or heap or static. Static variables means the memory is allocated statically and its life time is throughout the program execution time.

 

If a variable is allocated on the stack, we can see that stack size is increasing. If a variable is allocated on the heap (example malloc in C), we can see that heap size if increasing.

 

If I allocate a variable of 100 KB in static, which size will increase? Stack or Heap? Both are not correct. Your size of the .EXE file will increase..! This might be a surprise to many programmers in the begining. Similarly global variables are also allocated like static variables and its life time is throughout the program execution time.

 

Example for static variabales allocation is given below:

 


Source Code


#include <stdio.h>

 

void TestFunc()

{

    static int IsFirstTime = 0;

    if(IsFirstTime == 0)

    {

      printf("This function is called as a first time\n");

      IsFirstTime++;

    }

    else

    {

      IsFirstTime++;

      printf("This function has been called %d times so far\n", IsFirstTime);

    }

}

 

int main()

{

      int i;

      for(i = 0; i < 10; i++)

            TestFunc();

      return 0;

}

Output


This function is called as a first time

This function has been called 2 times so far

This function has been called 3 times so far

This function has been called 4 times so far

This function has been called 5 times so far

This function has been called 6 times so far

This function has been called 7 times so far

This function has been called 8 times so far

This function has been called 9 times so far

This function has been called 10 times so far

Press any key to continue . . .