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.
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
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.
Here's an excerpt from Section 6.7.1 (footnote 101) of the C99 standard (pdf):
And from Section 7.1.1, Paragraph 3 of the C++ standard (pdf):
Fun tidbits about
register
The C++ group (WG21) wants to deprecate
register
:Look what the C99 group (WG14) said about
register
(pdf) at a meeting: