Friday, July 29, 2016

C Basics - Overview of Storage Class in C

To fully define a variable one needs to mention not only its ‘type’ but also its ‘storage class’. In other words, not only do all variables have a data type, they also have a ‘storage class’.

A variable’s storage class tells us the following:
  • Where the variable would be stored (Memory or CPU registers).
  • What will be the initial value of the variable, if initial value is not specifically assigned.(i.e. the default initial value).
  • What is the scope of the variable; i.e. in which functions the value of the variable would be available.
  • What is the life of the variable; i.e. how long would the variable exist.
The "storage class" of a variable determines whether the item has a "global" or "local" lifetime. C calls these two lifetimes "static" and "automatic." An item with a global lifetime exists and has a value throughout the execution of the program. All functions have global lifetimes.

Automatic variables, or variables with local lifetimes, are allocated new storage each time execution control passes to the block in which they are defined. When execution returns, the variables no longer have meaningful values.

The placement of variable and function declarations within source files also affects storage class and visibility. Declarations outside all function definitions are said to appear at the "external level." Declarations within function definitions appear at the "internal level."

The exact meaning of each storage-class specifier depends on two factors:
  • Whether the declaration appears at the external or internal level
  • Whether the item being declared is a variable or a function
There are four storage classes in C:

Specifiers Storage Lifetime Scope Default Initializer
auto Stack memory Block Block Uninitialized
register Stack memory or CPU register Block Block Uninitialized
static Memory Program Block or compilation unit Zero
extern Memory Program Block or compilation unit Zero



Related topics:
Auto Storage Class in C   |   Register Storage Class in C   |   Static Storage Class in C   |   Extern Storage Class in C   |   Summary of Storage Class in C

List of topics: C Programming

No comments:

Post a Comment