Software & Finance





C Programming (Turbo C++ Compiler) - Static 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.

Example for static variabales allocation is given below:


Source Code


#include <stdio.h>


static char msg[] = "Welcome to my static function\n";

void DisplayWelcomeMessage()
{
       
printf(msg); 
// Accessing the msg static variable in sub function in the current file
}

int main()

{

    // Accessing the msg static variable in main function in the current file
    printf(msg);

    DisplayWelcomeMessage();

}

Output


Welcome to my static function

Welcome to my static function