Address of register variable

后端 未结 8 2084
灰色年华
灰色年华 2020-11-29 09:34

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

8条回答
  •  庸人自扰
    2020-11-29 10:14

    C and C++ are two different languages, with a large common subset. That's why some things are different between them.

    While I don't understand your question, register is (at least in C++) a hint that a variable might be accessed more frequently, and nothing more. In C, it means you can't take the address with the & unary operator, which made a certain amount of sense at the time. In the early days of C, it was expected that the compiler might not bother allocating memory for the variable, and so there would not necessarily be an address to take.

    (Computers normally have registers, which are quick-access parts of the CPU, and hence the fastest storage to access. A variable might live in a register, rather than in memory, if that caused better performance.)

    Nowadays, almost all compilers are sophisticated enough to do their own allocation better than the programmer can, so using register is almost always pointless.

提交回复
热议问题