Total Pageviews

Friday, 4 May 2012

Static Variables


Static Variables
A static variable is local to particular function. However, it is only initialised once (on the first call to function).

Also the value of the variable on leaving the function remains intact. On the next call to the function the the static variable has the same value as on leaving.

To define a static variable simply prefix the variable declaration with the static keyword. For example:

  void stat(); /* prototype fn */

               main()
                { int i;

                      for (i=0;i<5;++i)
                             stat();
                }

  stat()
                {    int auto_var = 0;
                     static int static_var = 0;
                    
                     printf( ``auto = %d, static = %d \n'',
                               auto_var, static_var);

                     ++auto_var;
                     ++static_var;
                }

Output is:

              auto_var = 0, static_var = 0
              auto_var = 0, static_var = 1
              auto_var = 0, static_var = 2
              auto_var = 0, static_var = 3
              auto_var = 0, static_var = 4

Clearly the auto_var variable is created each time. The static_var is created once and remembers its value.

No comments:

Post a Comment