Address of register variable

2019-01-06 19:45发布

In C, we cannot use & to find out the address of a register variable but in C++ we can do the same. Why is it legal in C++ but not in C? Can someone please explain this concept in-depth.

8条回答
不美不萌又怎样
2楼-- · 2019-01-06 20:31

The important thing to remember is that "register" is just a hint to the compiler (a pointless one at that; I've never seen any speed improvement, and most compilers probably just ignore it). C and C++ are both allowed to ignore your "advice" and keep the variable in memory. Of course, if you take the address of the variable, it will force it to assign a spot in memory.

C and C++ just have different rules about what you can do because they are different languages. The C++ designers decided to allow you to get the address of a register variable because it doesn't hurt anything; C doesn't allow you to do it because it would force it into memory.

Thinking about it more, C's restriction is probably for the same reason that variables had to be declared at the beginning of the block—the compiler can layout the memory for variables as it encounters them, without regard to how it's used later in the function.

查看更多
劫难
3楼-- · 2019-01-06 20:43

Here's an excerpt from Section 6.7.1 (footnote 101) of the C99 standard (pdf):

The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1). Thus, the only operator that can be applied to an array declared with storage-class specifier register is sizeof.

And from Section 7.1.1, Paragraph 3 of the C++ standard (pdf):

A register specifier has the same semantics as an auto specifier together with a hint to the implementation that the object 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 object is taken. —end note]

Fun tidbits about register

The C++ group (WG21) wants to deprecate register:

The register keyword serves very little function, offering no more than a hint that a note says is typically ignored. It should be deprecated in this version of the standard, freeing the reserved name up for use in a future standard, much like auto has been re-used this time around for being similarly useless.

Notes from the March, 2009 meeting:

The consensus of the CWG was in favor of deprecating register.

Look what the C99 group (WG14) said about register (pdf) at a meeting:

General agreement to deprecate the “auto” keyword. Should we ask WG21 to go back to the previous use of “register” (no address)? No, this will not fly with WG21.

查看更多
登录 后发表回答