4.3storage Class
4.3storage Class
• A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program.
• auto
• register
• static
• extern
Automatic
int fun()
{
return count;
}
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
}
Output: 1 2.
static variables are only initialized once and live till the end of the program. That is why they can retain their value between multiple function calls.
extern Storage Class
#include <stdio.h>
i=48;
#include <stdio.h>
void display ()
{ extern int x;
printf("%d\t",x);}
int main()
{ extern int x;
printf("%d\t",x);
display();
return 0;
}
int x=5;
Register Variable
• The register keyword is used to declare register variables. Register variables were supposed to be
faster than local variables.
• However, modern compilers are very good at code optimization, and there is a rare chance that using
register variables will make your program faster.
• Unless you are working on embedded systems where you know how to optimize code for the given
application, there is no use of register variables.
• The variables defined as the register is allocated the memory into the CPU registers depending upon the size of
the memory remaining in the CPU.
• The access time of the register variables is faster than the automatic variables.
• The initial default value of the register local variables is 0.
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
printf("%d",a);
}
#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error since we can not access the address of a register variable.
}
#include <stdio.h>
int main()
{
register int a = 10;
++a;
printf("Value of a : %d", a);
printf("\nEnter a value");
a=30;
--a;
printf("\n Value of a : %d", a);
return 0;
}
• Output:
Value of a : 11
Enter a value 30
Value of a : 29
Thank You