Storage Classes In C++ Auto Register Extern Mutable - C++ Programming Tutorial
C++ Course / Object-Oriented Programming / Storage Classes In C++ Auto Register Extern Mutable

Storage Classes In C++ Auto Register Extern Mutable

BLUF: Mastering Storage Classes In C++ Auto Register Extern Mutable is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Storage Classes In C++ Auto Register Extern Mutable

C++ is renowned for its efficiency. Learn how Storage Classes In C++ Auto Register Extern Mutable enables low-level control and high-performance computing in the tutorial below.

In C++, storage classes refer to reserved keywords that determine the duration, visibility, and memory location of variables (like auto, register, static, etc.) within a program. These classes dictate the allocation and deallocation of memory for variables in a C++ program.

Syntax

It has the following syntax:

Example

storage_class var_data_type var_name;

In this format, the storageclass denotes the storage class, vardatatype signifies the variable data types, and varname stands for the variable name.

Simple C++ Storage Classes Example

Let's consider a basic example to illustrate the storage classes in C++.

Example

Example

include <iostream>

using namespace std;

void add() {

    int x, y;

    cout << "Enter the value of X: ";

    cin >> x;

    cout << "Enter the value of Y: ";

    cin >> y;

    auto sum = x + y; // auto storage class

    register int fastAccess = sum; // register storage class

    cout << "Addition result (auto + register): " << fastAccess << endl; //dislay the result

}

int main() //main function

{

    add(); //calling function

    return 0;

}

Output:

Output

Enter the value of X: 5

Enter the value of Y: 10

Addition result (auto + register): 15

Types of Storage Classes in C++

There are primarily six categories of storage classes in C++.

Here is a chart displaying the duration, accessibility, and starting content.

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
Thread_local thread_local Thread Local

1. Automatic (auto) Storage Class in C++

The default storage class for local variables is the auto storage class. It is primarily used to specify the auto class for variables, allowing the declaration of variables with various data types such as int, double, and char. This class provides quicker memory access, orderly data structuring, and improves the clarity and efficiency of programs.

C++ Automatic Storage Class Example:

Let's consider an example to demonstrate the automatic storage class in C++.

Example

Example

#include <iostream>

#include <string> // using string header file

using namespace std; // using standard namespace

void autoStorage()

{

    auto w = 15; //declare and initialize int value

    auto x = 7.45;  //declare and initialize double value

    auto y = "Hello Cpp Tutorial"; //declare and initialize const char*

    auto z = 'T';     // declare and initialize char

    // printing the auto variables

    cout << w << " \n";

    cout << x << " \n";

    cout << y << " \n";

    cout << z << " \n";

}

int main() //main function

{

    autoStorage(); //using auto Storage Class

    return 0;

}

Output:

Output

15 

7.45 

Hello Cpp Tutorial 

T

Explanation:

In this instance, the auto storage class is employed for storing variables. The auto keyword is not applicable for explicitly declaring variables with the auto storage class.

2. Register Storage Class in C++

In C++, the "register" storage class is primarily used to direct the compiler to store a variable in a register. Register variables can be accessed more quickly compared to local or automatic variables, even though they serve the same purpose. By default, the register storage class has a value of 0.

The (&) operator is not compatible with a register variable. Variables declared with the "register" storage class possess automatic storage duration.

C++ Register Storage Class Example:

Let's consider a scenario to demonstrate the register storage class in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

void regisStorage() {

    register int count = 2; //Store variable in CPU register

    for (register int i = 0; i < 7; ++i) {

        count += i;

        cout << "i = " << i << ", count = " << count << endl;

    }

}

int main() //main function

{

    regisStorage(); //register storage class

    return 0;

}

Output:

Output

i = 0, count = 2

i = 1, count = 3

i = 2, count = 5

i = 3, count = 8

i = 4, count = 12

i = 5, count = 17

i = 6, count = 23

3. Static Storage Class in C++

In C++, the static storage class is employed to define variables that retain their value throughout the entire program execution. A static variable is defined by using the static keyword. While it is possible to declare a static variable multiple times, its value can only be assigned once.

Local variables are initialized at the beginning of program execution and are cleared when the program finishes. On the other hand, "static" variables are limited to a specific block or function scope, yet their values endure through multiple function invocations. These variables are commonly held in a distinct memory segment.

C++ Static Storage Class Example:

Let's consider an example to demonstrate the static storage class in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

void funct(); // Function declaration

static int counter = 8; // Global static variable

void funct() // Function definition

{ 

    static int x = 2; // Local static variable

    x++;

    cout << "x = " << x << ", Counter = " << counter << endl;

}

int main() //main function

{

    while (counter--) {

        funct();

    }

    return 0;

}

Output:

Output

x = 3, Counter = 7

x = 4, Counter = 6

x = 5, Counter = 5

x = 6, Counter = 4

x = 7, Counter = 3

x = 8, Counter = 2

x = 9, Counter = 1

x = 10, Counter = 0

4. External (extern) Storage Class in C++

In C++, the extern storage class is employed to establish a link to a global variable. It is defined outside of a function. Upon declaring an external variable in C++, it becomes accessible in any part of the entire program. The extern keyword proves to be advantageous when numerous C++ files need to access the same global variables and functions.

C++ External Storage Class Example:

Let's consider an illustration to showcase the 'extern' storage class with global variables in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

int x = 0; //define the extern variable 'x'

extern int x; // Declaring the extern variable

void externStorageClass() {

    cout << "Enter the Value of x: ";

    cin >> x;

    cout << "Value of the variable 'x', declared as extern: " << x << "\n"; //access the extern variable

    cout << "Modified value of the variable 'x', declared as extern: " << x << "\n"; //print the modified value of extern variable

}

int main() //Main function

{

    // Example of extern Storage Class

    externStorageClass();

    return 0;

}

Output:

Output

Enter the Value of x: 7

Value of the variable 'x', declared as extern: 7

Modified value of the variable 'x', declared as extern: 7

5. Mutable Storage Class in C++

In C++, the mutable storage class is employed to alter one or more data members of a class through a constant (const) function. It can be defined using the keyword mutable, primarily used to designate a specific data member of an object as modifiable. The 'mutable' keyword permits the modification of a data member of a const object, even within const member functions.

C++ Mutable Storage Class Example:

Let's consider an example to showcase the mutable storage class in C++.

Example

Example

#include <iostream>  

using namespace std; //using standard namespace

  

class MutableStorage {  

public:  

    int x; //integer value

    mutable int y;  //mutable variable

  

    MutableStorage() {  

        x = 24;  

        y = 15;  

    }  

};  

  

int main() //Main function

{  

    const MutableStorage t1;  

    cout <<"Before modifying the value of y: " <<t1.y <<endl;

    t1.y = 50; // Mutable member can be modified in a const object  

    cout << "After modifying the value of y: " <<t1.y; //display output

    return 0;  

}

Output:

Output

Before modifying the value of y: 15

After modifying the value of y: 50

6. Thread_local Storage Class in C++

In C++, the threadlocal storage class is a recent addition introduced in C++11. This storage class allows for defining objects as threadlocal. The thread_local object characteristics change based on how its variables interact with various storage specifiers like extern and static.

C++ Thread_local Storage Class Example:

Let's consider an example to showcase the thread_local storage class in C++.

Example

Example

#include <iostream>

#include <thread>

using namespace std; //using standard namespace

thread_local int x = 0; //Declaring thread local variable

void Thread_localTest() {

    

    x = 40; //the variable value

     

    cout << "Before modifying the value of x inside the Thread_localTest() function: " << x << " " << &x << endl; //print the address to its instance

}

int main() //main function

{

    

    x = 25; // modifying the variables value.

    

    cout << "After modifying the value of x inside the Main() function: " << x << " " << &x << endl; //display the address to val

    

    thread t1(Thread_localTest); //Creates a different instance of val

    t1.join();

    

    cout << "The value of x inside the Main() function: " << x << " " << &x << endl; //display the address to val

    return 0;

}

Output:

Output

After modifying the value of x inside the Main() function: 25 0x771e4eece73c

Before modifying the value of x inside the Thread_localTest() function: 40 0x771e4ee006bc

The value of x inside the Main() function: 25 0x771e4eece73c

Why storage classes are used in C++?

In C++, storage classes are used to regulate how variables are saved in memory, how long they exist, and where they may be accessed inside a program. C++ is essential for managing memory resources, improving efficiency, and assuring variable scope and lifespan. Here are some key reasons why storage classes are used in C++:

  • Memory Management: Different storage classes allow programmers to allocate memory for variables in various ways. For example, "auto" variables are typically allocated on the stack with automatic memory management, while "static" variables are allocated in a separate data segment with static memory management.
  • Lifetime Control: Storage classes determine the lifetime of variables. The "Auto" variables have a limited scope and are destroyed automatically when they go out of scope. The "Static" variables persist across function calls, retaining their values throughout the program's execution.
  • Performance Optimization: The "register" storage class allows programmers to suggest to the compiler that a variable should be stored in a CPU register, which can result in faster access. The "register" keyword can help improve performance in critical sections of code.
  • Variable Sharing: Several storage classes enable global variables to be shared across different translation units. It is useful to create global variables that may be accessed from multiple parts of a program, which facilitates the communication between different parts of the codebase.
  • Code Organization: Proper use of storage classes contributes to well-structured and organized code. By choosing the appropriate storage class for each variable, programmers can indicate the variable's intended scope, visibility, and lifecycle, which makes the code easier to understand and maintain.
  • C++ Storage Classes MCQs

  1. What will be the default initial value of a variable defined as static in C++?
  • Compiler Dependent
  • Random Garbage Value
  1. When a register variable is declared in C++ program, where is it allocated?
  • In the heap memory
  • In the stack memory
  • In the CPU register for quicker access
  • In the data segment
  1. In which storage class, the const keyword is used to declare variables in C++?
  • Auto Storage Class
  • Register Storage Class
  • Extern Storage Class
  • Static Storage Class

a) Automatic Storage Class

  1. What is the expected output of the code snippet below?
Example

#include <iostream>

#include <thread>

using namespace std; //using standard namespace

int main()

{

    register int x;

    for (x = 1; x < 3; x++) {

        cout<<"Cpp Tutorial Class: "<< x <<endl;

    }

    return 0;

}
  • Cpp Tutorial Class: 1
  • Cpp Tutorial Class: 1 Cpp Tutorial Class: 2
  • Cpp Tutorial Class: 1 Cpp Tutorial Class: 2 Cpp Tutorial Class: 3
  • None of the Above

Cpp Tutorial Class: 2

  1. Which of the following storage class is the default storage class for global variables in C++?
  • Static
  • Register
  • Auto
  • Extern

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience