Search code examples
c++pass-by-referenceregister-keyword

Pass a register variable by reference


I have seen code where variables with the register keyword are passed by reference into functions.

Version 1:

inline static void swap(register int &a, register int &b) 
{
    register int t = a; 
    a = b; 
    b = t; 
}

Version 2:

inline static void swap(register int a, register int b) 
{
    register int t = a; 
    a = b; 
    b = t; 
}

What are the differences between the two versions?

To my understanding, a and b are kept in registers so the reference operator shouldn't have any effect as the changes made to the values in these registers should persist across the caller-callee boundary, without the use of the reference operator.


Solution

  • In C programs, you cannot take the address of a register variable.

    register int x;
    int * p = &x; // Compiler error
    

    This is sometimes useful in macros to prevent clients from taking the address of something that should only be used as a value.

    The use of register is deprecated in the C++11 standard (see [depr.register]). In C++ it is legal to take the address of a register variable, but it not legal in the latest revision of the C++11 standard to declare an alignment for a register variable with alignas. See 7.6.2 Alignment specifier

    Other than preventing the use of alignas() and causing a syntax error when used outside local, register does nothing in C++. Since it's deprecated and because I can't imagine any reason you would want to prevent the alignment of variable used inside a macro, you should avoid using register in C++ code.

    To answer the question: In C++ there is no difference between your code and the equivalent code with register removed, so your "two versions" are different in the obvious way.