C Tutorial/Language/static Variables

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Static variable

#include <stdio.h>
int g = 10;  
main(){
    int i =0; 
    void f1();
    f1();            
    printf(" after first call \n");
    f1();            
    printf("after second call \n");
    f1();            
    printf("after third call \n");
}
void f1()
{
    static int k=0;  
    int j = 10;             
    printf("value of k %d j %d",k,j);
    k=k+10;
}
value of k 0 j 10 after first call
      value of k 10 j 10after second call
      value of k 20 j 10after third call

Static versus automatic variables

#include <stdio.h>
void test1(void){
  int count = 0;
  printf("\ntest1   count = %d ", ++count );
}
void test2(void){
  static int count = 0;
  printf("\ntest2   count = %d ", ++count );
}
int main(void)
{
  int i;
  for(i = 0; i < 5; i++ )
  {
    test1();
    test2();
  }
  return 0;
}
test1   count = 1
     test2   count = 1
     test1   count = 1
     test2   count = 2
     test1   count = 1
     test2   count = 3
     test1   count = 1
     test2   count = 4
     test1   count = 1
     test2   count = 5