C/Data Type/Static

Материал из C\C++ эксперт
Версия от 13:22, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Define and use static variable

<source lang="cpp">

  1. include <stdio.h>

void f(void); int main(void) {

 int i;
 for(i = 0; i < 10; i++) 
     f();
 return 0;

} void f(void) {

 static int count = 0;
 count++;
 printf("count is %d\n", count);

}


      </source>


Define static variable inside function

<source lang="cpp">

  1. include <stdio.h>

int g = 10; void f(); main() {

   int i =0; 
   f();
   printf(" after first call \n");
   f();
   printf("after second  call \n");
   f();
   printf("after third  call \n");

} void f() {

   static int k=0; 
   
   int j = 10;
   
   printf("k= %d j= %d",k,j);
   
   k = k + 10;

}


      </source>


Demonstrate the use for permanent and temporary storage

<source lang="cpp">

  1. include <stdio.h>

int main() {

   int i;
   for (i = 0; i < 3; ++i) {
       int temporary = 1;
       static int permanent = 1;
       printf("Temporary %d Permanent %d\n",temporary, permanent);
       ++temporary;
       ++permanent;
   }
   return (0);

}


      </source>


Find out the address of a static variable in a function

<source lang="cpp">

  1. include <stdio.h>

int myFunction(int n); long old=0; long current=0; int main() {

  int k = 4,i;
  long diff;
  i =myFunction(k);
  printf("i = %d\n",i);
  diff = old - current;
  printf("stack overheads are %16lu\n",diff);

} int myFunction(int n) {

   int j;
   static int staticVariable=0;
   if(staticVariable==0){
       old =(long) &j;
   }
   if(staticVariable==1){
       current =(long) &j;
   }
   staticVariable++;
   printf("the address of j and staticVariable is %16lu %16lu\n",&j,&staticVariable);
   if(n<=0){
       return(1);
   }else{
       return(n*myFunction(n-1));
   }

}


      </source>


Static versus automatic variables

<source lang="cpp">

  1. include <stdio.h>

/* Function test1 with an automatic variable */ void test1(void) {

  int count = 0;
  printf("\ntest1   count = %d ", ++count );

} /* Function test2 with a static variable */ void test2(void) {

  static int count = 0;
  printf("\ntest2   count = %d ", ++count );

} int main() {

  int i = 0;
  for( i = 0; i < 5; i++ )
  {
    test1();
    test2();
  }

}


      </source>