Storage classes in C++

Posted

The purpose of storage classes in C++ are used to specify the lifetime and visibility of a variable. The allocation of the variable and how each variable is controlled by the compiler depends on which storage class it uses in the code.

In C++ there are five types of storage classes which are:

  1. Global variables
  2. Local variables
  3. Register variables
  4. Static variables
  5. Extern variables

 

Global variables

These variables are declared at the start of the program, before all the user created functions and the int main() function. The advantage of this allows the global variables to be accessed anywhere in the code.


using namespace std;

int global_variable; // Global variable
void function();

int main()
{
.....
}

 

Local variables

Local variables are also known as Automatic variables because they are only visible within the function it is declared and its lifetime is same as the lifetime of the function as well. Once the execution of function is finished, the variable is destroyed.  By default all local variables are auto, so we don’t have to explicitly add keyword auto before declaring a local variable. Default value of such variable is garbage.

#include <iostream.h>
int test()
{
 int x;
 x = 200;
 return x;
}

 

Register variables

Stores the variable in the CPU instead of the RAM. Almost similar to a local variable but has the advantage of increasing the access speed and making the program run faster. Register variables can only be declared only within a block, which means you cannot have global or static register variables.


#include <iostream>

using namespace std;

int main()
{
int num1, num2;
register int sum;

cout << ("\nEnter the Number 1 : ");
cin >> num1;

cout << ("\nEnter the Number 2 : ");
cin >> num2;

sum = num1 + num2;

cout << ("\nSum of Numbers : %d", sum);

return(0);
}

 

Static variables

Initialized & allocated storage only once at the beginning of program execution. It can be used only within the function where it is declared but destroyed only after the program execution has finished. An ideal time to use a static variable would be to save values in a recursive function.


void static_addition()
{
static int i = 10;
i++;
cout << i;
}
int main()
{
static_addition(); // Output = 11
static_addition(); // Output = 12
static_addition(); // Output = 13
}

 

Extern variables

Extern variables declared allows us to access a variable in a file which is declared as a global variable in one file and then can be used in a separate file.