What's a good example of register variable usage in C?

Viewed 31714

I'm reading through K&R and came to the small section on register variables, and was wondering if people here have some good examples of this put into practice.

From section 4.7 in K&R:

The register declaration looks like
register int x;
register char c;

To be clear, I'm just hoping to see some cool code samples. I (am pretty sure that I) understand the subject matter so don't feel the need to type up a verbose explanation (unless you want to).

6 Answers

There is no good example of register usage when using modern compilers (read: last 15+ years, and note that this answer is from 2008) because it almost never does any good and can do some bad. When you use register, you are telling the compiler "I know how to optimize my code better than you do" which is almost never the case. One of three things can happen when you use register:

  • The compiler ignores it, this is most likely. In this case the only harm is that you cannot take the address of the variable in the code.
  • The compiler honors your request and as a result the code runs slower.
  • The compiler honors your request and the code runs faster, this is the least likely scenario.

Even if one compiler produces better code when you use register, there is no reason to believe another will do the same. If you have some critical code that the compiler is not optimizing well enough your best bet is probably to use assembler for that part anyway but of course do the appropriate profiling to verify the generated code is really a problem first.

In general i agree with Robert, but as any good rule this one has exceptions as well.
If you working on deeply embedded system you might know better than compiler how to optimize the code for your specific application on your specific hardware architecture.

But in 99% of cases Roberts explanation good for embedded word as well.

Another common case is when implementing low-level interpreters. Keeping some state in registers, eg. virtual machine stack pointer, can reduce the memory access significantly and speed up you code.

See vmgen — a generator of efficient virtual machine interpreters for an example of the optimization (5.2 Top of stack caching).

Well This is a Question that needs multiple answers because there are multiple coding contexes: from the high level language perspective, the mid level and low level (down to assembly) since the C language can call assembly routines.

The reason for using assembly instead of C is exavtly because of performance issues encountered during development soz yes there is a need for the register keyword but no it is not working as intended by developer in many cases

Related