What is a Storage Class in C++ and its types?

Published on Nov 11,2019 9.5K Views

What is a Storage Class in C++ and its types?

Storage class in C++ defines the lifetime & visibility of the variable/functions. Lifetime is the duration till which the variable remains active & visibility is the accessibility of a variable from different modules of the program. This helps to trace the existence of a particular variable during the runtime of a program. In this storage classes blog, we will look at various storage classes used in C++.

Let’s begin.

What is Storage Class In C++?

Every variable in C++ has data type and storage class. Data type specifies the type of data that can be stored in a variable such as int, float, char etc. Storage class controls two different properties of a variable: lifetime and scope.

You would have seen every variable has a data type, but you might not have seen any storage class attached to a variable so far. Actually, if you do not define a storage class, compiler automatically assigns a default storage class to it. A variable’s storage class gives information about the storage location of variable in memory, default initial value, scope of the variable and its lifetime.

Types of Storage Class

There are five storage classes in a C++ Program:

  • auto
  • register
  • static
  • extern
  • mutable

Let’s discuss each one of the storage classes in detail. 

Auto Storage Class

Automatic (auto) storage class is the default storage class for all local variables, which are declared inside a function or a block. The auto keyword is rarely used while writing a C++ program.

The scope of auto variables is within the function or block where they have been declared & it cannot be accessed outside that function or block. It can also be accessed within nested blocks within the parent block/function in which the auto variable was declared.

You can access auto variables outside their scope using a pointer variable. You need to point to the same memory location where the variables are residing. 

Its lifetime is the same as the lifetime of the function. Once the execution of a function is finished, the variable is destroyed.

By default, garbage value is assigned to them while declaration.

Syntax:

datatype var_name1 [= value];

or

auto datatype var_name1 [= value];

In the above example, two variables are defined with the same storage class. Auto can only be used to define local variables i.e. within functions.

Register Storage Class

As the name suggests, the register storage class is used to declare register variables. All the functionalize of the register variable is the same as the auto variable except that the compiler tries to store these variables in the register of the microprocessor if a free register is available. If a free register is not available, these are then stored in the memory only.

Thus, operations on register variables are much faster than that of other variables that are stored in the memory during the runtime of the program. 

Generally, few variables that need to be accessed frequently in a program are declared within register storage class to improve the running time of the program. The address of a register variable cannot be obtained using pointers.

The maximum size of the variable is equal to the size of the register (i.e. one word approximately). It can’t have a unary ‘&’ operator applied to it as it does not have a memory location.

Syntax:

register datatype var_name1 [= value];

Example:

{
   register int  pi;
}

Defining ‘register’ does not mean that the variable will be stored in a register. It might be stored in a register depending on hardware and implementation restrictions.

Let’s look at an example of register & auto storage classes.

Example:

#include <stdio.h> 
using namespace std;

// declaring the variable which is to be made extern 
// an intial value can also be initialized to x 
int x; 
  
void autoStorageClass() 
{ 
  
    printf("nDemonstrating auto classnn"); 
  
    // declaring an auto variable (simply 
    // writing "int a=32;" works as well) 
    int num = 32; 
  
    // printing the auto variable 'a' 
    printf("Value of the variable 'num'"
           " declared as auto: %dn", 
           num); 
  
    printf("--------------------------------"); 
} 
  
void registerStorageClass() 
{ 
  
    printf("nDemonstrating register classnn"); 
  
    // declaring a register variable 
    register char c = 'G'; 
  
    // printing the register variable 'b' 
    printf("Value of the variable 'c'"
           " declared as register: %dn", 
           c); 
  
    printf("--------------------------------"); 
} 
  

int main() 
{ 
  
    // To demonstrate auto Storage Class 
    autoStorageClass(); 
  
    // To demonstrate register Storage Class 
    registerStorageClass(); 
  
    return 0; 
}

Output:

Output - Storage class in C++ - EdurekaStatic Storage Class

The static storage class is used to declare static variables. Static variables preserve their value(i.e. the last value) even when they are out of their scope. Static variables are initialized only once & exist till the termination of the program. 

The memory is allocated only once to the static variable & no new memory is allocated because they are not re-declared. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

Syntax:

static datatype var_name1 [= value];

Example:

#include <iostream>
 
void function(void);
 
static int c = 5; // Global static variable
 
main() {
   while(c--) {
      function();
   }
   
   return 0;
}

void function( void ) {
   static int cnt = 2; 
   cnt++;
   std::cout << "cnt is " << cnt ;
   std::cout << " and c is " << c << std::endl;
}

Output:

Static Storage Class in C++ - EdurekaExtern Storage Class

The extern storage class is required when the variables need to be shared across multiple files. Extern variables have global scope and these variables are visible outside the file in which they are declared. The extern variable is visible to all the programs. It is used if two or more files are sharing the same variable or function.

The lifetime of the extern variables is as long as the program in which it is declared is terminated. A normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/ definition in any function/ block. 

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.

Syntax

extern datatype var_name1;

Example

#include <iostream>
int cnt;
extern void write_extern();
main() {
   cnt = 5;
   write_extern();
}

Second File: support.cpp

#include <iostream>
extern int cnt;

void write_extern(void) {
   std::cout << "Count is " << cnt << std::endl;
}

Here, extern keyword is being used to declare cnt in another file. Now compile these two files as follows −

$g++ main.cpp support.cpp -o write

This will produce write executable program, try to execute write and check the result as follows −

$./write

5

Moving ahead with storage class in C++, let’s have a look at the last one, i.e, Mutable storage class.

Mutable Storage Class

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

At last, let’s look at the comparison table to understand the differences between different storage classes.

Storage Class

Keyword

Lifetime

Visibility

Initial Value

Automatic

auto

Function Block

Local

Garbage

External

extern

Whole Program

Global

Zero

Static

static

Whole Program

Local

Zero

Register

register

Function Block

Local

Garbage

Mutable

mutable

Class

Local

Garbage

Now after going through the above C++ programs, you would have understood what are different storage classes in C++ & how to implement them. I hope this blog is informative and added value to you.

Thus we have come to an end of this article on ‘Storage classes in C++’.

If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.