File handling
How to print Heart Pattern with C

Storage classes

Storage Classes

Every single variable has a storage class which defines all the features of that variable. It guides the compiler about the storage place of the variable, its initial value, scope ( visibility level ) and lifetime ( global or local ).

There are four storage classes in c language

  • auto
  • static
  • extern
  • register

Auto

The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default. Since these variables are declared inside a function, therefore these can only be accessed inside that function. There is no need to put ‘auto’ while declaring these variables because these are by default auto.

#include<stdio.h>

int sum(int n1, int n2){
  auto int s;        //declaration of auto(local) variable
  s = n1+n2;
  return s;
}
int main(){
  int i = 2, j = 3, k;
  k = sum(i, j);
  printf("sum is : %d\n", k);
  return 0;
}

sum is : 5

Static

Static variables retain the value of the variable between different function calls.A variable declared as static once initialized, exists till the end of the program. If a static variable is declared inside a function, it remains into existence till the end of the program and not get destroyed as the function exists (as in auto). If a static variable is declared outside all the functions in a program, it can be used only in the program in which it is declared and is not visible to other program files(as in extern).

#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

 

0 1 2 3

Extern

We use extern keyword before a variable to tell the compiler that this variable is declared somewhere else. Basically, by writing extern keyword before any variable tells us that this variable is a global variable declared in some other program file.

#include<stdio.h>
 
int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;

The value of x is 10
The value of y is 50

Register

Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.

#include<stdio.h>
int main()
{
    register int n = 20;
    int *ptr;
    ptr = &n;
    printf("address of n : %u", ptr);
    return 0;
}

prog.c:2:1: warning: return type defaults to ‘int’ [-Wimplicit-int]main(){
^
prog.c: In function ‘main’:
prog.c:5:1: error: address of register variable ‘n’ requested
ptr = &n;
^

Comments are closed.