Why cant register variables be made global?

2020-06-04 09:04发布

While reading from a site a read that you can not make a global variable of type register.Why is it so? source: http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/regdef.htm

标签: c
9条回答
闹够了就滚
2楼-- · 2020-06-04 09:48

Because it would be senseless. Global variables exist all the time the application is working. There surely is no free processor register for such a long time ;)

查看更多
乱世女痞
3楼-- · 2020-06-04 09:48

The register word is used in C/C++ as request to the compiler to use registers of processor like variables. A register is a sort of variable used by CPU, very very fast in access because it isn't located in memory (RAM). The use of a register is limited by the architecture and the size of the register itself (this mean that some could be just like memory pointers, other to load special debug values and so on).

The calling conventions used by C/C++ doesn't use general registers (EAX, EBX and so on in 80x86 Arch) to save parameters (But the returned value is stored in EAX), so you could declare a var like register making code faster.

If you ask to make it global you ask to reserve the register for all the code and all your source. This is impossible, so compiler give you an error, or simply make it a usual var stored in memory.

查看更多
姐就是有狂的资本
4楼-- · 2020-06-04 09:53

The register keyword has a different meaning than what its name seems to indicate, nowadays it has not much to do with a register of the processing environment. (Although it probably once was chosen for this.) The only text that constrains the use of a variable that is declared with register is this

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier

So it implements a restriction to automatic variables (those that you declare in a function) such that it is an error to take the address of such a variable. The idea then is that the compiler may represent this variable in whatever way pleases, as a register or as an immediate assembler value etc. You as a programmer promise that you wouldn't take an address of it. Usually this makes not much sense for global variables (they have an address, anyhow).

To summarize:

  • No, the register keyword is not ignored.
  • Yes, it can only be used for stack variables if you want to be standard conformant
查看更多
登录 后发表回答