C/Data Type/Static

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

Define and use static variable

#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);
}


Define static variable inside function

  
#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;
}


Demonstrate the use for permanent and temporary storage

#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);
}


Find out the address of a static variable in a function

#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));
    }
}


Static versus automatic variables

#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();
   }
}