"register" keyword in C?

Solution 1:

It's a hint to the compiler that the variable will be heavily used and that you recommend it be kept in a processor register if possible.

Most modern compilers do that automatically, and are better at picking them than us humans.

Solution 2:

I'm surprised that nobody mentioned that you cannot take an address of register variable, even if compiler decides to keep variable in memory rather than in register.

So using register you win nothing (anyway compiler will decide for itself where to put the variable) and lose the & operator - no reason to use it.

Solution 3:

It tells the compiler to try to use a CPU register, instead of RAM, to store the variable. Registers are in the CPU and much faster to access than RAM. But it's only a suggestion to the compiler, and it may not follow through.

Solution 4:

I know this question is about C, but the same question for C++ was closed as a exact duplicate of this question. This answer therefore may not apply for C.


The latest draft of the C++11 standard, N3485, says this in 7.1.1/3:

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 ... —end note ]

In C++ (but not in C), the standard does not state that you can't take the address of a variable declared register; however, because a variable stored in a CPU register throughout its lifetime does not have a memory location associated with it, attempting to take its address would be invalid, and the compiler will ignore the register keyword to allow taking the address.