Storage Classes in C

In C, storage classes define the scope, visibility, and lifetime of variables or functions within a program. The following are the four main storage classes in C:

  • auto
  • register
  • static
  • extern

Let us discuss them one by one with examples:

auto storage class

  • The default storage class for local variables.
  • Scope: Local to the block or function where it’s defined.
  • Lifetime: Only during the execution of the block or function.

register storage class

  • Suggests that the variable be stored in a CPU register instead of RAM for faster access.
  • Scope: Local to the block or function where it’s defined.
  • Lifetime: Only during the execution of the block or function.
  • Note: The compiler can ignore this suggestion.

static storage class

  • For local variables, it extends the lifetime of the variable to the entire runtime of the program, but the scope remains local to the block or function where it’s defined.
  • For global variables and functions, it restricts the visibility to the file where it’s defined.
  • Scope: Local for block or function, file-level for global.
  • Lifetime: Entire runtime of the program.

extern storage class

  • Used to declare a global variable or function that is defined in another file.
  • Scope: Global, across multiple files.
  • Lifetime: Entire runtime of the program.
  • Important for sharing variables and functions across different files in a multi-file program.

Example: Storage Classes in C

Let us see an example of implementing storage classes in C:

Output

In this example:

  • localVar is a local variable with auto storage class, so it gets reinitialized every time the function is called.
  • regVar is a register variable, intended for quick access, and it also gets reinitialized every time.
  • staticVar retains its value between function calls because of the static storage class.
  • globalVar is a global variable with extern storage class, and it retains its value across the entire program.

Above, you saw how staticVar and globalVar behave differently compared to localVar and regVar.

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

String Functions in C
Char Functions in C
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading