Static Variables

Consider the following function which will not work correctly;


void foo(void)   /* will not work correctly */
{
   int first=1;  /* first is true */
   if (first)
   {
      ... /* do something */
      first = 0; /* set first to false */
   }
   else
   {
      ... /* do something else */
   }    
}

The intent was to do one thing if this was the first call to the function, 
but, otherwise to do something else.  Unfortunately, it will not work as the 
variable first is created each time the function is called.  

Although first is set to false, on exiting the function, the variable is 
lost.  (The memory location is freed for use by other auto variables).  Thus, 
the next time, the function is called, the variable is again created and 
intialized to 1.

The following will work as intended.

void foo(void)  
{
   static int first=1;  /* first is true */
   if (first)
   {
      ... /* do something */
      first = 0;  /* now set it to false */
   }
   else
   {
      ... /* do something else */
   }    
}

The only modification is the declaration of first as a static int.  Note that 
a static int is created only once and it retains its value throughout.  Thus, 
in this case, first is set to 1 on the first call.  The program changes it to 
0.  On subsequent calls the value is 0.