Storage classes in C Plus Plus

Storage class for a variable specify lifetime and visibility of a variable within a program.
 

Lifetime of a variable

Lifetime of a variable refer to the duration for which a variable remains active.
 

Visibility of a variable

Visibility of a variable refer scope of the variable.
 
There are four type of storage class
  1. Automatic
  2. External
  3. Static
  4. Register
 

Automatic

Every normal variable has automatic default class, its lifetime limited to the function and visibility is restricted to the function.
 
auto int age=20;
 

External storage class

A variable declared outside the function is called external variable or global variable, and external variable is accessible by the every individual function, but if declare the variable with same name within a function we unable to access that external variable but we can access if we use extern keyword with the declaration of a variable.
 
int age=20;
void message(){
extern int age;
cout<<age;
}
 

static storage class

static variable initialize once for the whole program execution.
 
void count(){
// Without static
int c=0;
c++;
cout<< c << endl;
}
count(); // 1
count(); // 1



void count(){
// with static
static int c=0;
c++;
cout<< c << endl;
}
count(); // 1
count(); // 2
 

Register storage class

Normally variable stored in Primary Memory of computer, we want to store variable value register other than primary memory, we use register storage class, it makes fast accessing of variable which will also make program more fast than variable stored in primary memory.
 
#include<iostream>
#include<conio.h>
using namespace std;
void count(){
register int c=0;
c++;
cout<<c<<endl;
}
int main(){
count();
count();

getch();
return 0;
}
© 2016 - 2022, All Rights are Reserved.