"register" keyword in C? – Dev

The best answers to the question “"register" keyword in C?” in the category Dev.

QUESTION:

What does the register keyword do in C language? I have read that it is used for optimizing but is not clearly defined in any standard. Is it still relevant and if so, when would you use it?

ANSWER:

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.

ANSWER:

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.

ANSWER:

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.

ANSWER:

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.