How to store a C++ variable in a register

ashutosh kumar picture ashutosh kumar · Apr 9, 2013 · Viewed 22.3k times · Source

I would like some clarification regarding a point about the storage of register variables: Is there a way to ensure that if we have declared a register variable in our code, that it will ONLY be stored in a register?

#include<iostream>

using namespace std;

int main()
{
    register int i = 10;// how can we ensure this will store in register only.
    i++;
    cout << i << endl;
    return 0;
}

Answer

Joseph Mansfield picture Joseph Mansfield · Apr 9, 2013

You can't. It is only a hint to the compiler that suggests that the variable is heavily used. Here's the C99 wording:

A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.

And here's the C++11 wording:

A register specifier is a hint to the implementation that the variable so declared will be heavily used. [ Note: The hint can be ignored and in most implementations it will be ignored if the address of the variable is taken. This use is deprecated (see D.2). —end note ]

In fact, the register storage class specifier is deprecated in C++11 (Annex D.2):

The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated.

Note that you cannot take the address of a register variable in C because registers do not have an address. This restriction is removed in C++ and taking the address is pretty much guaranteed to ensure the variable won't end up in a register.

Many modern compilers simply ignore the register keyword in C++ (unless it is used in an invalid way, of course). They are simply much better at optimizing than they were when the register keyword was useful. I'd expect compilers for niche target platforms to treat it more seriously.