C Storage Class Specifier

Storage classes determines the visibility or lifetime of a variable or function.

There are five storage classes in C.

  1. auto
  2. register
  3. static
  4. extern
  5. typedef

Auto Storage Class

The auto storage class stands for automatic and the variable defined as automatic have a local scope i.e. accesible only within the block in which it is created. A variable is automatically is in auto storage class if not explicitly defined.

Syntax

auto int var;

Example Code

#include<stdio.h>
int main(void)
{
    auto int a = 4;
    {
        auto int a = 8;
        printf("a = %d\n",a);
    }
    printf("a = %d\n",a);

    return 0;
}

Output

a = 8
a = 4

Register Storage Class

The register strorage class is used to define local variables that will be stored in registers instead of RAM. Since registers do not have memory location, '&' operator cannot be used.

Syntax

register int var;

Static Storage Class

Defining a static local variable instruct the compiler to keep the local variable in existence throughtout the lifetime of a program instead of creating and destroying it each time the variable goes out of scope. This allows preservation of its value in between function calls.

Syntax

static int var;

Example Code

#include<stdio.h>
int x = 5;    //global variable

int main(void)
{
    printf("x = %d\n",x);
    fun();  //fun() function call
    fun();
    fun();
    return 0;
}

int fun()
{
    static int var = 1;		//Retains old value instead of value 1
    printf("var = %d\n",var);
    var++;
}

Output

x = 5
var = 1
var = 2
var = 3

Extern Storage Class

The extern storage class is used to give reference to a global variable or function that has been already created in some other file. Extern variables cannot be initialized with a value.

When one file references a variable declared in another file using extern, then they must be compiled together to generated a combined object code.

Syntax

extern int var;

Typedef Storage Class

The typedef storage class is used to create an alias name of an existing datatype.

Syntax

typedef dataType alias_name;

Example Code

#include<stdio.h>
 
typedef struct Car
{
	float price;
	int air_bags;
}car;	//Alias for struct Car => car

int main(void)
{
    //Alias for unsigned long long => very_long
    typedef unsigned long long very_long;
    
    very_long var = 1234567890;
    car bmw;
    bmw.price = 40000.00;
    bmw.air_bags = 4;
    printf("var = %llu\n",var);
    printf("bmw price = %.2f\n",bmw.price);
    printf("bmw no. of airbags = %d\n",bmw.air_bags);
    
    return 0;
}

Output

var = 1234567890
bmw price = 40000.00
bmw no. of airbags = 4

Trending

C Programming

Remember to follow community guidelines and don't go off topic.