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");
          update();
          printf("Calling update for the 2nd time\n");
          update();
          printf("Calling update for the 3rd time\n");
          update();
          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);
    }

  Output:
  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


1 comment:

  1. Dell Laptop Service center are giving repair service at the door. We should high quality Dell out of warranty Laptop Repair, removal of virus, screen removal, wireless network set up, battery removal, motherboard replacement to several other are offered at budget friendly price and it’s Negotiable. We can fix them all in time by our well experience and certified technicians. If you want to repair your laptop in front of your eyesight, than you may call us: 7217871051

    ReplyDelete