register in C served for two purposes:
- Tell the compiler that the variable should be stored in a register for performance. This usage is currently out of date.
- Prevent the programmer from using the variable in such a way as to prevent it from being stored in the register. This use is only an outdated IMO.
It looks like const , which
- Tips the compiler that a variable can be stored in read-only memory.
- Prevents programming from writing a variable
As an example, consider this simplified function:
int sum(const int *values, size_t length) { register int acc = 0; for (size_t i = 0; i < length; ++i) { acc += values[i]; } return acc; }
The programmer wrote register to save the drive from the stack, avoiding writing memory every time it is updated. If the implementation is changed to something like this:
// Defined in some other translation unit void add(int *dest, int src); int sum(const int *values, size_t length) { register int acc = 0; for (size_t i = 0; i < length; ++i) { add(&acc, values[i]); } return acc; }
The variable acc can no longer be stored in the register when its address is taken to call add() , because the registers have no address. Thus, the compiler will flag &acc as an error, informing you that you probably destroyed the performance of your code by not allowing acc from living in a register.
This was much more important in the early days when compilers were dumber and variables could live in one place for an entire function. Currently, a variable can spend most of its life in the register, moving to the stack only temporarily when its address is busy. That is, this code:
void debug(const int *value); int sum(const int *values, size_t length) { int acc = 0; for (size_t i = 0; i < length; ++i) { acc += values[i]; } debug(&acc); return acc; }
would make acc live on the stack for the whole function in older compilers. Modern compilers keep acc in the register until the debug() call.
Modern C code usually does not use the register keyword.
Tavian Barnes May 26 '16 at 16:31 2016-05-26 16:31
source share