CPP – Storage Classes

A storage class defines the scope and lifetime (visibility) of a variable or a function in a program’s lifetime. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program:

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

Auto Storage Class

By Default, all variables and functions that you create in your program are bound with auto storage class. It doesn’t make any effect on the variable if you include the auto keyword or not.

int var;
auto int var;

In this case, the scope of the variable var will be same in both lines.

Static Storage Class

Static Storage classes are used to maintain the variable throughout the lifetime of the program instead of creating and destroying the variable on each function calls. Static can also be used to declare a global variable.

#include <iostream>
using namespace std;

static int var = 20; // Global Variable

void add (int a )
  static int res; // Local Variable
  res = var + a;
  cout << "Sum is : " << res << endl;
int main()
  int x = 10;
  return 0;

Sum is : 30

Register Storage Class

The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can’t have the unary ‘&’ operator applied to it (as it does not have a memory location).

int main()
 register int x = 10;
 return 0;

Extern Storage Class

The extern storage class is used to give a reference to a global variable that is visible to ALL the program files. When you use ‘extern’ the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file.

#include <iostream>
int count;
extern void useExtern();
main() {
   count = 5;

2nd File in which the useExtern() function is defined.

#include <iostream>
using namespace std;
extern int count;

void useExtern(void) {
   cout << "Count is " << count << endl;

Count is 5

Mutable Storage Class

The mutable specifier applies only to class objects, it allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.

Written by Anandesh

I am a #Linux lover and very much excited about technology and new thing. Love to #read_books. Curiosity is my best teacher. I am still☺️ understanding myself.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

CPP – DataTypes

CPP – Finishing the Basics