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

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

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

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

 

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

myVar is 5

Leave a Reply