C++ register Keyword

The register keyword in C++ is a storage class specifier that suggests to the compiler that the variable should be stored in a CPU register for faster access. Variables declared with register are typically used in performance-critical sections of code where speed is important, such as loops.

Modern compilers often optimize variable storage automatically, so the register keyword has become less relevant. It is retained in C++ for compatibility with older code but is rarely needed now a days.


Syntax

</>
Copy
register data_type variable_name;
register
The keyword suggesting that the variable should be stored in a CPU register.
data_type
The type of the variable (e.g., int, char, etc.).
variable_name
The name of the variable.

Examples

Example 1: Using register for Loop Optimization

In this example, you will learn how the register keyword can be used to suggest faster access to a loop counter.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    register int counter; // Suggest storing the counter in a CPU register

    for (counter = 0; counter < 5; ++counter) {
        cout << "Counter: " << counter << endl;
    }

    return 0;
}

Output:

Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4

Explanation:

  1. The register keyword is used to suggest that the variable counter be stored in a CPU register for faster access.
  2. The loop iterates from 0 to 4, printing the value of counter at each step.
  3. Modern compilers may ignore the register keyword and optimize variable storage automatically.

Example 2: Using register with a Local Variable

In this example, you will learn how to use the register keyword for a local variable in a function.

</>
Copy
#include <iostream>
using namespace std;

int sumOfN(int n) {
    register int sum = 0; // Suggest storing 'sum' in a register
    for (int i = 1; i <= n; ++i) {
        sum += i;
    }
    return sum;
}

int main() {
    int n = 10;
    cout << "Sum of first " << n << " numbers: " << sumOfN(n) << endl;
    return 0;
}

Output:

Sum of first 10 numbers: 55

Explanation:

  1. The register keyword suggests faster storage for the sum variable in the function.
  2. The loop calculates the sum of the first n natural numbers by adding each integer to sum.
  3. The result is returned and printed in the main function.

Key Points about register Keyword

  1. The register keyword suggests that the variable be stored in a CPU register for faster access.
  2. Modern compilers often ignore the register keyword and optimize variable storage automatically.
  3. Register storage is only a suggestion to the compiler and is not guaranteed.
  4. A variable declared with register cannot have its address taken using the & operator.