Javatpoint Logo
Javatpoint Logo

Storage classes in C++

Storage classes are keywords in C++ programming that determine the lifespan, scope, and storage location of variables inside a program. Storage classes govern how variables are kept in memory, how long they persist, and how and where they may be retrieved.

C++ has four major storage classes:

  • auto: It is the default storage class for local variables declared within a block or function. Variables with the "auto" storage class have automatic storage duration, meaning they are created when the block or function is entered and destroyed when it's exited. They are typically stored on the stack. the "auto" keyword is rarely used directly because local variables are considered "auto" by default.
  • register: The "register" storage class is used to instruct the compiler to store a variable in a register, which is a tiny, fast-access storage space within the CPU. However, the compiler is free to ignore this request, and modern compilers often optimize register usage automatically. Variables with the "register" storage class also have automatic storage duration.
  • static: Variables declared with the "static" storage class have static storage duration, meaning they are allocated memory for the entire program's duration. They are created when the program starts and destroyed when it terminates. The "static" variables have local scope within a block or function, but their values persist across function calls. They are typically stored in a separate data segment of memory.
  • extern: The "extern" storage class is used to declare variables that are defined in other source files. It extends the visibility of a variable to the entire program. "extern" variables have global scope, and they are often used to share variables across multiple source files.

These storage classes help programmers to control the memory usage and lifecycle of variables, which is crucial for managing resources efficiently and writing maintainable code. The choice of storage class depends on the variable's intended use, scope, and lifetime within the program.

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. This flexibility enables efficient utilization of memory resources based on the variable's usage and scope.
  • 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. This control over variable lifetimes ensures memory is allocated and deallocated appropriately, preventing memory leaks.
  • 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. While modern compilers often make their own decisions about register allocation, using the "register" keyword can help improve performance in critical sections of code.
  • Sharing Data: The "extern" storage class enables variables to be shared across different translation units (source files). It is essential for creating global variables that can be accessed from multiple parts of a program, facilitating 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, making the code easier to understand and maintain.

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
Storage Class Keyword Lifetime Visibility Initial Value
Automatic auto Function Block Local Garbage
Register register Function Block Local Garbage
Mutable mutable Class Local Garbage
External extern Whole Program Global Zero
Static static Whole Program Local Zero

The auto Storage Class in C++

In C++, the storage classes play a vital role in determining the scope, lifetime, and memory allocation of variables. One such storage class is 'auto', which is the default class assigned to variables declared within a block.

Properties of auto Storage Class:

The auto-storage class is associated with several key attributes that define its behavior:

Scope: Local

The auto-storage class confines the scope of variables to the block in which they are declared. It means that the variables are accessible only within that specific block.

Default Value: Indeterminate (Garbage Value)

Upon declaration, variables of the auto storage class are not initialized automatically. As a result, they contain indeterminate or garbage values until explicitly assigned a valid value.

Memory Location: RAM

Variables with the auto storage class are allocated memory in the computer's RAM (Random Access Memory), which is a fast and volatile type of memory.

Lifetime: Limited to Block Scope

The lifespan of auto-storage class variables is restricted to the block in which they are defined. Once the execution flow exits the block, the variables are automatically destroyed, releasing the memory they occupy.

Example:

Let us examine an example to demonstrate the behavior of the auto-storage class:

Output:

Understanding the auto storage class
32 
3.2 
JavaTpoint
G

The extern Storage Class in C++ for Global Variables

In C++, the storage classes play a crucial role in managing the scope, memory allocation, and lifetime of variables. Among these, the 'extern' storage class stands out by allowing variables to be defined in a different block and accessed across multiple files.

Properties of the extern Storage Class:

The 'extern' storage class is characterized by specific attributes that dictate its behaviour:

Scope: Global

The 'extern' storage class gives a variable global scope. It means that the variable can be accessed and used anywhere within the program, even outside the block where it was declared.

Default Value: Zero Initialization

By default, the 'extern' variables are initialized to zero. It implies that if the variable is not explicitly assigned a value, it will hold a value of zero.

Memory Location: RAM

Similar to other variables, the 'extern' variables are allocated memory in the computer's RAM (Random Access Memory). This memory space is used to store the variable's value during program execution.

Lifetime: Lasts Until Program Termination

The lifetime of an 'extern' variable extends throughout the entire duration of the program. It is created when the program starts and retains its value until the program terminates.

Example:

Let us explore an example to demonstrate the behavior of an 'extern' storage class with global variables:

Output:

Understanding the extern class
Value of the variable 'x', declared as extern: 0
Modified value of the variable 'x', declared as extern: 2

The static Storage Class in C++

In the world of C++, storage classes play a vital role in managing variables' scope, lifetime, and memory allocation. Among these, the 'static' storage class stands out for its unique ability to preserve values even after they leave their scope.

Properties of the static Storage Class:

The 'static' storage class is characterized by specific attributes that govern its behavior:

Scope: Local

The 'static' storage class confines variables to their local scope. However, unlike other local variables, the 'static' variables retain their value across function calls.

Default Value: Zero Initialization

The 'static' variables are automatically initialized to zero if not explicitly assigned a value. This ensures a predictable starting point for their values.

Memory Location: RAM

Like other variables, the 'static' variables are allocated memory in the computer's RAM (Random Access Memory). This memory space holds the variable's value throughout the program's execution.

Lifetime: Lasts Until Program Termination

The 'static' variables persist in memory until the program concludes. Their values are preserved across function calls, making them a suitable choice for maintaining state information.

Example:

Let us delve into an example to illustrate the behavior of the 'static' storage class:

Output:

For static variables: 1
For static variables: 2
For Non-Static variables: 1
For Non-Static variables: 1

The register Storage Class in C++

In the realm of C++, storage classes wield influence over the behavior of variables, governing aspects like scope, memory allocation, and lifetime. The 'register' storage class, once utilized for optimizing variable access, is introduced in this article. However, it's important to note that as of C++17, the 'register' keyword is deprecated, and modern compilers often optimize variable storage and access automatically.

Properties of the register Storage Class:

The 'register' storage class is distinguished by specific traits that characterize its functionality:

Scope: Local

Similar to the 'auto' variables, 'register' variables possess local scope, confined to the block in which they are declared.

Default Value: Indeterminate (Garbage Value)

Like 'auto' variables, 'register' variables are not automatically initialized. Their initial values are indeterminate until explicitly assigned.

Memory Location: CPU Register or RAM

While 'register' variables aim to reside within a CPU register for faster access, this behaviour depends on the availability of free registers. If no register is available, these variables are stored in RAM like ordinary variables.

Lifetime: Limited to Block Scope

The lifespan of 'register' variables is bounded by the block in which they are declared. Upon exiting the block, the variables cease to exist.

Address Unavailability: Cannot Obtain Address

It's important to highlight that obtaining the address of a 'register' variable using pointers is not permissible due to the potential incompatibility with the register storage strategy.

Example:

Here is an example showcasing the concept of the 'register' storage class:

Output:

Illustrating the register class
Value of the variable 'b' declared as register: G

Mutable and thread_local

In the C++ programming language, storage class specifiers play a crucial role in controlling variable properties such as scope, lifetime, and mutability. This article explores two specific storage class specifiers, 'mutable' and 'thread_local', shedding light on their functionalities with practical examples.

Mutable Storage Class:

In situations where you need to modify specific data members within a const function while keeping other members unchanged, the 'mutable' keyword comes into play. The 'mutable' keyword allows modifying a data member of a const object, even within const member functions.

Properties of the mutable Storage Class:

The 'mutable' storage class has the following properties:

Scope:

Limited to the containing class.

Effect on Const Functions:

Allows modification of data members within const member functions.

Linkage and Lifetime:

Similar to other non-mutable members.

Purpose:

Permits specific modifications to data members without violating const-correctness.

Example:

Output:

20

Next TopicC++ Arrays





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA