C++ Storage Classes

C++ Storage Classes

Storage class is used to define the lifetime and visibility of a variable and/or function within a C++ program.
Lifetime refers to the period during which the variable remains active and visibility refers to the module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
  1. Automatic
  2. Register
  3. Static
  4. External
  5. Mutable


Automatic Storage Class

The auto storage class is the default storage class for all local variables.
{
   int mount;
   auto int month;
}

Register Storage Class

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
Note: We can't get the address of register variable.
{
   register int  miles;
}


Static Storage Class
The static variable is initialized only once and exists till the end of a program. It retains its value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
#include <iostream>
 
// Function declaration
void func(void);
 
static int count = 10; /* Global variable */
 
main() {
   while(count--) {
      func();
   }
   
   return 0;
}

// Function definition
void func( void ) {
   static int i = 5; // local static variable
   i++;
   std::cout << "i is " << i ;
   std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

External Storage Class

The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or function.

First File: main.cpp

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

Second File: support.cpp

#include <iostream>

extern int count;

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

No comments:

Post a Comment