C Tutorial/Language/static Variables — различия между версиями

Материал из C\C++ эксперт
Перейти к: навигация, поиск
м (1 версия: Импорт контента...)
 
(нет различий)

Текущая версия на 13:32, 25 мая 2010

Static variable

<source lang="cpp">#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;

}</source>

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

<source lang="cpp">#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;

}</source>

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