Kind of variable | Life time in C |
---|---|
Global variable | During the entire execution of the program. |
static global variable | During the entire execution of the program. |
static local variable | During the entire execution of the program. |
Parameter variable | From the start of execution of the function to the end of the execution of the function |
Local variable | From the definition of the variable in the function to the end of the execution of the function |
|
That's why:
|
|
That's why the life time of parameter and local variables is the duration of the function call !!!
|
|
|
#include <stdio.h> void f( ) { int i = 1234; // Normal local (created when f() is called) static int j = 1234; // Static local (created using ds, ONCE !) i++; j++; printf( "i = %d, j = %d\n", i, j ); } int main( int argc, char* argv[] ) { f(); f(); f(); f(); f(); } |
Output:
i = 1235, j = 1235 // i "forgets" i = 1235, j = 1236 // j remembers !!! i = 1235, j = 1237 i = 1235, j = 1238 i = 1235, j = 1239 |
Explanation:
|
How to run the program:
|