This blog is under construction

Sunday, 13 May 2012

Static storage class in C

Static Variables:
Static variable is of type internal or external based on its declaration.  If it is declared outside the function block, then it is static global.  Otherwise, it's similar to auto variable and it will be active within the block in which it is declared.  A static variable is initialized only once and it is never reinitialized after that. It will retain its latest value even when the function or block execution is over.

Static variable example:
int func() {
       static int num = 10;
       return 0;

Example C program using static variables:
    #include <stdio.h>
    void update();
    // static global
    static int val = 1000;

    int main() {
          printf("Calling update for the 1st time\n");
          printf("Calling update for the 2nd time\n");
          printf("Calling update for the 3rd time\n");
          return 0;

    void update() {
          // static internal
          static int num = 100;
          num = num * 10;
          printf("Value of num:%d\n", num);
          val =  val - 5;
          printf("Value of val:%d\n", val);

  jp@jp-VirtualBox:~/$ ./a.out
  Calling update for the 1st time
  Value of num:1000
  Value of val:995
  Calling update for the 2nd time
  Value of num:10000   // old value of num is 1000 => 1000 * 10 = 10000
  Value of val:990
  Calling update for the 3rd time
  Value of num:100000
  Value of val:985

No comments:

Post a Comment