Storage Classes - C Data Type

C examples for Data Type:union

Introduction

The storage classes include the following:

  • auto,
  • register,
  • extern, and
  • static.

They determines the variable scope and lifetime.

Auto

The default storage class for local variables is auto.

You can be explicitly specified with the auto keyword.

Memory for auto variables is allocated when the code block is entered and freed on exit.

The scope of auto variables is local to the block where they are declared.

Demo Code

int main(void) {
   auto  localVar = 0; /* auto variable */
}

Register

The register storage class tells the compiler to put the variable in a CPU register instead of RAM memory to provide better performance.

Variables of the register storage class cannot use the address-of operator & since registers do not have memory addresses.

Demo Code

int main(void) {
  register int counter; /* register variable */
}

Use of the register keyword has become deprecated.

External

The external storage class references a variable or function defined in another compilation unit.

A compilation unit includes a source file and header files.

Functions default to the external storage class.

/* app.c */
extern void foo(void); /* declared function */
int main(void) {
  foo(); /* external function call */
}

/* func.c */
void foo(void) {} /* defined function */

When extern with a global variable tells the compiler that the variable is defined else where.

/* app.c */
int globalVar; /* defined variable */

int main(void) {
  globalVar = 1;
}

/* func.c */
extern int globalVar; /* declared variable */

int foo(void) {
  globalVar++;
}

Static

The static storage class restricts the scope of a global variable or function to the compilation unit where it is defined.

/* Only visible within this compilation unit */
static int myInt;
static void myFunc(void) {}

Local variables may be declared as static to make the function preserve the variable for the duration of the program.

A static local variable is only initialized once.

/* Store number of calls to this function */
void myFunc(void) {
  static int count = 0;
  count++;
}

Volatile

A volatile modifier tells the compiler that a variable's value may be changed by external.

volatile int var; /* recommended order */
int volatile var; /* alternative order */

Related Tutorials