Wednesday, October 28, 2015

Static Variable Inside C Function.

#include <stdio.h>

#define TEST_3


void FuncA ()
{
#ifdef TEST_0
  // 0 value initialization only happen once if defined 'static'.
  static int StaticVar=0;
#endif
#ifdef TEST_1
  // 0 value initialization happen every time when FuncA is called.
  int StaticVar=0;
#endif
#ifdef TEST_2
  // When not give inital value, system set StaticVar to '0'
  // Changed value will stay next time when FuncA is called as StaticVar
  // is defined with keyward 'static'.
  static int StaticVar;
  printf("StaticVar is : %d\n",StaticVar);
  StaticVar = 2;
#endif
#ifdef TEST_3
  // When no 'static', system set StaticVar to a random value.
  // (I think it depends on what value in stack.)
  // But in test it seems, StaticVar keep same value as it's retrieving 
  // value from same postion in stack.
  int StaticVar;
  printf("StaticVar is : %d\n",StaticVar);
  StaticVar = 3;
#endif

  printf("StaticVar is : %d\n",StaticVar);
  StaticVar++;

}


void main()
{
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  FuncA();
  printf ("====Done====\n"); 

}
The results after defining different test cases:

Test_0
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 1
StaticVar is : 2
StaticVar is : 3
StaticVar is : 4
StaticVar is : 5
====Done====
Test_1
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
StaticVar is : 0
====Done====
Test_2
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 0
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
StaticVar is : 3
StaticVar is : 2
====Done====
Test_3
qyang@lubuntu-laptop:~$ ./Learn_static 
StaticVar is : 134513947
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
StaticVar is : 4
StaticVar is : 3
====Done====

No comments: