Site icon TestingDocs.com

C Storage Classes

Overview

In this tutorial, we will learn about C storage classes. Storage classes define the lifetime and scope of the variables and functions in the program. There are different storage classes defined in the C language:

 

auto Storage Class

The automatic storage class is the default storage class for all the local variables in the functions. We can use the auto keyword to declare the local variable. Since this is the default we can also omit the keyword in the variable declaration.

The general syntax to declare an automatic  variable:

auto <data_type> <variable_name>;

<data_type> <variable_name>;

auto <data_type> <variable_name> = <initializer>;

Example:

int number = 20; // default
auto int sum = 0;

static Storage Class

The auto variables are stored in that Stack. The automatic variables would have the block scope. There are visible within the block or function there are declared.

The static storage class allows the compiler to keep the lifetime of the variable to the whole program. When we declare a local variable as a static variable it will persist the value between the function calls.

The general syntax to declare a static variable:

static <data_type> <variable_name>;

register Storage Class

The register storage class is used to store a variable in a CPU register instead of a RAM location( Random Access Memory). Storing a variable in the CPU register allows quick access time for the variable. A variable that is frequently accessed in the program can be stored in the register.

C Compiler does not guarantee that the register variable will be stored in a CPU register. The general syntax to declare a register variable:

register <data_type> <variable_name>;

Example

register int loopCounter = 0;

 

extern Storage Class

The extern keyword is used to give a reference to a global variable that is visible in other source files. When we have multiple source files and we define a global variable or function in one file but might be used in other files. We can use the extern keyword to give reference to a defined global variable or function.  The extern variable cannot be initialized as it refers to the previously defined variable.

The general syntax to declare an extern variable:

extern <data_type> <variable_name>

Example:

extern int N;

C Tutorials

C Tutorials on this website can be found at:

https://www.testingdocs.com/c-language-tutorial/

Exit mobile version