Thursday, July 1, 2010

Static and register storage class in C programming




   Static variables in C Language

Occasionally it is desirable to declare a variable within a function whose value will be stored throughout the execution of the program. If we declare a variable within a function ( auto ) then the variable is allocated and de-allocated each time the function is invoked. But if we declare a static variable within a function then when the function is exited , the variable retains its value.

#include<stdio.h>
void count(int , int);
void main()
{
int num1,num2;
clrscr();
printf("Enter two numbers:-");
scanf("%d%d",&num1,&num2);
count(num1,num2);
printf("Another two numbers:-");
scanf("%d%d",&num1,&num2);
count(num1,num2);
printf("%d",c);
getch();
}
void count(int a,int b)
{
static int c;
a=a+b;
c++;
printf("Sum is :-%d",a);
printf("\nYou have send %d pair of values.",c);
}

 use of static variable in C Language

#include <stdio.h>
int Static( );
int Dynamic( );
static int count = 0;
void main()
{
   int i;
   clrscr();
   printf("\nProgram for use of static variable in function\n");
   printf("count is %d\n",count);
   for (i=0; i<9; i++)
   {
      count ++;
      printf("count = %d, static count = %d, dynamic count = %d\n",count, Static(), Dynamic());
   }
   getch();
}
int Static( )
{
   static int i = 0;  
   return( ++i );
}
int Dynamic(  )
{
   int i = 0; 
   return( ++i );
}

Register variable

Registers are special storage areas within a computers CPU.The actual Arithmetic and Logical operations are done within Registers and these operations are carried out by transferring datas from computers memory to registers , the indicated operations are carried out and then datas are transferred to memory. This process is executed several times in a program execution.
For programs the execution time can be reduced  if we store certain values within register rather than memory. In C a variable can be assigned this storage class simply by preceding the type declaration with the keyword register. Register variables are closely related to auto variables , except address operator ( & ) cannot be applied on them.

Any Question ? Please put your comments....

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner