MASIGNASUKAv102
6510051498749449419

C++ Storage Classes - Learn With AVRK

Add Comments
Friday, September 3, 2021

Storage Classes in C++ Programming Language

In the C++ programming language, there are variables and each variable has a data type. When we declared the variable, the compiler assigned the storage class by default and that storage class is used to define the lifetime and visibility of a variable or function within the program.

Lifetime refers to the period during which the variable remains active whereas visibility refers to the module of a program during which the variable is accessible.

Loading...

We used five types of storage in C++ program, which are as follows -

  1. Automatic
  2. Register
  3. Static
  4. External
  5. Mutable

Storage Class Keyword Lifetime Visibility Initial Value
Automatic auto Function Block Local Garbage
Register register Function Block Local Garbage
Static static Whole Program Local Zero
External extern Whole Program Global Zero
Mutable Mutable Class Local Garbage

Automatic Storage Class

All local variables have a default storage class which is an automatic storage class. The automatic storage class has a pre defined keyword that is auto. The auto keyword is automatically applied to all local variables.
{
    auto int c; 
    float c= 1.24; 
}
The above example defines two variables with the same storage class, auto can only be used within functions.

Register Storage Class

Register storage class is employed to declare register variables. Register variable is similar to auto variable. It allocates memory in registers as compared to RAM. It's size is same as the size of register.  This makes operations on register variables much faster than other variables stored in memory during runtime. The point to note is that we will not get the address of the register variable.

register int counter=0; 


Static Storage Class

Static variables are initialized only once and exist until the end of the program. It retains it's value between multiple function calls.

The default value of a static variable is 0 which is provided by the compiler.

#include <iostream>
using namespace std;
void func() 
{    
    static int i=0; /*static variable */
    int j=0; /*local variable */
    i++;
    j++;
    cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
    func();
    func();
    func();
}

Output -

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1


External Storage Class

The extern variable is visible to all programs. It is used when two or more files are sharing the same variable or function.
extern int counter=0;    

Also check out this : 
Call by value and call by reference - Learn With AVRK
Learn With AVRK

Learn With AVRK