Skip to main content

Auto Storage Class in C

Auto Storage Class

  • The "auto" storage class in C is the default storage class for variables declared within a function. Variables declared with the "auto" storage class are also called "automatic variables" or "local variables."

  • When a function is called, the memory for an "auto" variable is allocated on the stack, and the variable is initialized with the value provided in its declaration or with the garbage value if no value is provided.

  • The variable is only accessible within the scope of the function in which it is declared and is destroyed when the function exits.

  • This means that the variable is not visible or accessible outside of the function in which it is defined, making it a local variable.

Syntax for using "auto" storage class:

void my_function() {
auto int x = 5; // x is an "auto" variable with an initial value of 5
// x can be used within the scope of my_function
}

Example 1

#include <stdio.h>

void func()
{
auto int x = 10; // x has an auto storage class
printf("Value of `auto` variable 'x' is = %d", x);
}

int main()
{
func();
return 0;
}
Output:

Explanation

  • The variable x is declared within the scope of the func function and has an automatic storage class.

  • This means that it is created each time the function is called and destroyed when the function returns. The value of x is not retained between function calls.

note

It's important to note that the "auto" storage class is not used often as it is the default storage class, and variables that are declared inside a function are automatically considered as "auto" storage class, unless explicitly specified as other storage class.