Software & Finance





C Programming (Turbo C++ Compiler) - Static Global Variables





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.

IsEntered is a static global variable and can be used by any function defined in the file.


Source Code


#include <stdio.h>

 

static int IsEntered = -1;

 

void DisplayStatus()

{

    if(IsEntered == 1)

        printf("Function Enters\n");

    else if(IsEntered == 2)

        printf("Function Exits\n");

    else

        printf("Not initialized\n");

}

 

void EnterFunction()

{

    IsEntered = 1;

}

 

void ExitFunction()

{

    IsEntered = 2;

}

 

int main()

{

    DisplayStatus();

    EnterFunction();

    DisplayStatus();

    ExitFunction();

    DisplayStatus();

 

    return 0;

}

Output


Not initialized

Function Enters

Function Exits