开发者

Why do we need to suggest a variable to be stored in register?

开发者 https://www.devze.com 2023-01-18 08:40 出处:网络
As I know that in C we could use the keyword \"register\" to suggest to the compiler that the variable should be stored in the CPU register. Isn\'t it true that all va开发者_如何学Goriables that invol

As I know that in C we could use the keyword "register" to suggest to the compiler that the variable should be stored in the CPU register. Isn't it true that all va开发者_如何学Goriables that involved in CPU instructions will be eventually stored in CPU registers for execution?


The register keyword is a way of telling the compiler that the variable is heavily used. It's true that values must usually be loaded temporarily into registers to perform calculations on them. The name comes from the idea that a compiler might keep the variable in a register for the entire duration that it is in scope, rather than only temporarily when it is being used in a calculation.

The keyword is obsolete for the purpose of optimisation, since modern compilers can determine when a variable is heavily used (and when it does not have its address taken) without help from the programmer.


You should not use that register keyword. It is an antique relic, maintained for backward compatibility. Most compilers will ignore it (by default).

There could be exceptions but they are very rare, consult your compiler manual.

Isn't it true that all variables that involved in CPU instructions will be eventually stored in CPU registers for execution?

Yes, that is true. But CPU registers are limited so variables are usually LOAD/STOREd from 'normal' memory and live in a register only briefly. The register keyword is (was) a way of indicating high priority variables that should occupy a register longer. Like the i in for(i = 0; ...).


In old times, compilers weren't that smart as they are today. It was a hint from the programmer to the compiler that this variable should be stored in a register to allow fast access/modification. Today, almost any decent compiler implements clever registers allocation algorithms that beats the mind of humans.


Most variables will be loaded into registers for a short while...as long as necessary to do what needs to be done with them. The register keyword hints that they should be kept there.

Compilers' optimization has gotten so much better, though, that the register keyword isn't very helpful. In fact, if your compiler respects it at all (and many don't), it could even mess you up (by tying the compiler's hands, making certain optimizations impossible). So it's a pretty bad idea these days.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号