Why storage classes are used in C++?
Storage classes are used in C++ to manage variables in terms of memory usage, scope, and lifetime. They help optimize the program by:
- Determining scope: Storage classes control where variables can be accessed within a program.
- Managing lifetime: Some storage classes allow variables to persist throughout the program execution, while others limit them to specific blocks.
- Memory optimization: By specifying how and where variables are stored, storage classes can reduce unnecessary memory usage, improving performance.
- Variable sharing: Some storage classes allow global variables to be shared across multiple files, ensuring proper communication between different parts of a program.
Types of Storage class
- Automatic
- Register
- Static
- External
- Mutable
Automatic
It is a default storage class for all nearby variables. They are called local variables that are declared interior a function or a block. Auto variables can only be called within the function or a block in which they had been declared, i.e., cannot be accessed outside from that function or block. We can also access them inside nested blocks and the parent block where the declaration of the car variable is. Pointer variables are used to access auto variables outdoor their scope. We point to the same region in the memory where variables are stored. Its lifespan depends on the function's lifetime(same as the function's lifetime), i.e., when a function's execution is complete, the variable is destroyed. Using the default, they are given a rubbish fee whenever declared.
Example
#include <iostream>
using namespace std;
void autoStorageClass()
{
cout << "Demonstration of auto storage class\n";
// Declare an auto variable
// We do not need data-type declaratiion
auto a = 50;
auto b = 5.2;
auto c = "AutoStorageClass";
auto d = 'A';
// Displaying the auto variables
cout << a << " \n";
cout << b << " \n";
cout << c << " \n";
cout << d << " \n";
}
int main()
{
// Demonstrating auto Storage Class
autoStorageClass();
return 0;
}
You can also try this code with Online C++ Compiler
Run CodeOutput
Demonstration of auto storage class
50
5.2
AutoStorageClass
A
You can try and compile with the help of online c++ compiler.
Register
We declare register variables using the register storage class. A sign-in variable functions further to an auto variable. The most effective exception is that the compiler tries to save these variables in the microprocessor's sign-up if one is available.
If no accessible registers are available, they are entirely saved in memory. Operations on register variables are much faster than other variables saved in memory during run-time.
A few variables that need to be accessed often in a program are usually declared in the register storage class. This helps increase the program's execution speed. A register variable's address cannot be found via pointers. The variable's most apparent size is equal to the register's largest size. We cannot use the '&' operator because there is no memory location for it.
Example
#include <iostream>
using namespace std;
void registerStorageClass()
{
cout << "Demonstration of register storage class\n";
// declaration of a register variable
register char c = 'G';
//Lets dispkay the register variable
cout << "Value of 'c' which is"
<< " declared as register: " << c;
}
int main()
{
// Demonstrating the Storage Class
registerStorageClass();
return 0;
}
You can also try this code with Online C++ Compiler
Run CodeOutput
Demonstration of register storage class
Value of, which is declared as register: G
Static
Static variables are declared using the storage class. Static variables maintain their cost even if they may be out of doors their scope. They're initialized as soon as and exist till the program is terminated. The memory for the static variable is simplest allotted once, and no extra memory is allocated as it is not re-declared.
We can access global static variables everywhere in the code. The compiler assigns the value zero to them by default. In C++, whilst we use static on a class data member, all objects share only one copy of that member in that class.
Example
#include <iostream>
using namespace std;
// Function that contains static variables
// memory is retained during execution
int staticFun()
{
cout << "Static variables: ";
static int count = 0;
count++;
return count;
}
// Function that contains non-static variables
// Destroying memory
int nonStaticFun()
{
cout << "Non-Static variables: ";
int count = 0;
count++;
return count;
}
int main()
{
// Printing the static variables parts
cout << staticFun() << "\n";
cout << staticFun() << "\n";
// Printing the non-static variables parts
cout << nonStaticFun() << "\n";
cout << nonStaticFun() << "\n";
return 0;
}
You can also try this code with Online C++ Compiler
Run CodeOutput
static variables: 1
static variables: 2
Non-Static variables: 1
Non-Static variables: 1
External
We need this storage class whilst we want the variables to be shared throughout several files. Outside variables have a global scope and may be seen outside of the file where they were declared. The whole program can see it, and it's far utilized whilst the same variable or characteristic is shared via or more documents.
The lifetime of the external variable is the same as the lifetime of the program in which they were declared. A regular global variable will also be rendered external by using the 'extern' keyword before its statement or description in any function or block.
The variable can not be initialized while you use 'extern' because it points the variable name to a previously decided storage address.
Example
#include <iostream>
using namespace std;
// Declaring the variable which is to
// be made extern an initial value can
// also be initialized to m
int m;
void externStorageClass()
{
// We tell compiler that variable
// m is an extern variable. It's been defined somewhere else (above the main function)
extern int m;
// printing the extern variables
cout << "Initialized value of 'm'which is "
<< "declared as extern: " << m << "\n";
// value of 'm' modified
m = 15;
// printing the modified values of
// extern variables
cout
<< "Modified value of 'm'"
<< " declared as extern: "
<< m;
}
int main()
{
// Demonstration of extern Storage Class
externStorageClass();
return 0;
}
You can also try this code with Online C++ Compiler
Run CodeOutput
Initialized value of 'm' which is declared as extern: 0
Modified value of 'm' declared as extern: 15
Mutable
Only class objects have a mutable specifier. This enables a member of an object to override a const member function. This is, a const member function can exchange a mutable member.
Even if you don't need the function to update different contributors of the class/struct, you would possibly want to exchange one or greater information participants. The usage of the const function executes this. The mutable keyword makes this task easy to finish.
Example
#include <iostream>
using std::cout;
class Test
{
public:
int m;
// Defining mutable variable n
// which can be modified
mutable int n;
Test()
{
m = 5;
n = 20;
}
};
int main()
{
// Our t1 is set to constant
const Test t1;
// We are trying to change the value
t1.n = 50;
cout << t1.n;
// Not commenting below the lines
// will throw errors
// t1.m = 8;
// cout << t1.m;
return 0;
}
You can also try this code with Online C++ Compiler
Run CodeOutput
50
The extern Storage Class in C++ for Global Variables
The extern storage class is used to declare global variables and functions that can be accessed across multiple files in a C++ program. When a variable is declared with extern, it tells the compiler that the variable exists in another file, but it can be used in the current file without redefining it. This is helpful when dealing with large projects, allowing for modular code development. For example:
// In file1.cpp
int count = 10; // Global variable
// In file2.cpp
extern int count; // Referring to the variable declared in file1.cpp
Using extern ensures that the same global variable can be accessed across multiple files without duplication, supporting better code organization.
The register Storage Class in C++
The register storage class in C++ suggests that a variable should be stored in the CPU's register rather than RAM for faster access. This is typically used for variables that are frequently accessed, such as loop counters. The register keyword is merely a hint to the compiler, and modern compilers may ignore it if they decide it’s not optimal. A register variable has local scope, meaning it cannot be accessed globally, and unlike normal variables, it cannot have its address taken using the & operator.
Example:
void quickCounter() {
register int counter; // Hint to store in a CPU register
for (counter = 0; counter < 100; ++counter) {
// fast access due to potential register storage
}
}
Mutable and thread_local
In C++, the mutable and thread_local keywords serve specialized purposes in managing variable behavior.
- Mutable: The mutable storage class allows a member of an object to be modified, even if the object is declared const. Normally, const objects cannot have their members changed, but using mutable gives flexibility for specific variables, particularly in scenarios where certain internal states may change without altering the object's logical state.
Example:
class MyClass {
mutable int counter; // Can be modified even in const objects
public:
void increment() const {
counter++; // allowed due to mutable
}
};
- thread_local: The thread_local storage class ensures that a variable is unique to each thread in a multithreaded environment. Each thread gets its own copy of the variable, ensuring no data races occur between threads. This is useful in concurrent programming where variables need to maintain thread-specific states.
Example:
thread_local int threadVar = 0; // Each thread has its own instance of threadVar
This makes thread_local critical for applications that require thread-specific storage to maintain data integrity across multiple threads.
Frequently Asked Questions
​​How many storage specifiers are there in C++?
C++ has five storage specifiers: auto, register, static, extern, and mutable. Each specifier controls the scope, lifetime, and visibility of variables. They allow programmers to manage memory usage, optimize performance, and handle variable accessibility efficiently.
​​What are the 4 storage classes?
The four main storage classes in C++ are auto, register, static, and extern. These classes define a variable's lifetime, scope, and memory location, providing greater control over how variables are used and stored in a program.
​​Is mutable a storage class?
Yes, mutable is a storage class in C++. It allows modification of class members even in const objects. This is useful when certain member variables need to change while maintaining the overall immutability of the object itself.
Conclusion
In this article, we mentioned the different methods that we can use as storage class's in C++ programs and what they are and their roles. With that, you must create programs that use storage classes to express the attributes of variables and methods. Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? Attempt our Online Mock Test Series on Code360now!