Storage Classes

Defines when, where and how storage is allocated and de-allocated for a variable

 

auto

  • Default storage class
  • Temporarily allocated storage for the duration of the block it is contained within
    • i.e. allocated upon initialisation within the block, and deallocated at the end of the block
  • New storage is allocated each time the program executes the specific 'local' block
    • Upon completion of a specific local block local variables are released and no longer have any meaningful value
#include <stdio.h>
int main()
{
   for (int i = 1; i <= 3; i++)
   {
	   auto int myVar = 42;
	   printf("myVar is: %d \n", myVar++) ; //notice increment operator on myVar++
   }
   return 0;
}

Compile & Run:

myVar is: 42
myVar is: 42
myVar is: 42

 

 

static

  • Default for Global variables
  • Permanently allocated storage for the duration of the program
  • Value of a static variable in a function is retained between repeated function calls to the function
#include <stdio.h>

int main()
{
   for (int i = 1; i <= 3; i++)
   {
	   static int myVar = 42;
	   printf("myVar is: %d \n", myVar++) ;
   }
   return 0;
}

Compile & Run:

myVar is: 42
myVar is: 43
myVar is: 44

 

 

register

  • Used to define variables that should be stored in a register rather RAM
  • Therefore maximum size is the same as the register size
  • Can not have the unary & operator applied, as it has no address
  • Used for frequent/fast access, e.g. counter
#include <stdio.h>

int main()
{
   for (register int i = 1; i <= 3; i++)
   {
	   printf("value of i in register is: %d \n", i) ;
   }
   return 0;
}

Compile & Run:

value of i in register is: 1
value of i in register is: 2
value of i in register is: 3

 

 

extern

 

Used to call upon a variable that is defined within an external file

#include <stdio.h>

extern int myVar;

myFunc()
{
    printf("myVar is %d \n", myVar);
}
#include <stdio.h>

int myVar = 5 ;

int main ()
{
    myFunc() ;
    return 0 ;
}

 

Compile & Run (gcc extern-1.c extern-2.c -o target):

myVar is 5

Leave a Reply