c c++ register

用register关键字修饰的变量,在C语言中是不可以用&操作符取地址的。因为编译器如果接受了程序员的建议把变量存入寄存器,它是不存在虚拟地址的。但在C++中,用register修饰的变量可以用&操作符取地址,这是我在一段代码中发现的。如果程序中显式取了register变量的地址,编译器一定会将这个变量定义在内存中,而不会定义为寄存器变量。

C99指出了

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)

C++0x也说:
the hint
can be ignored and in most implementations it will be ignored if the address of the object is taken.

还有一个评说是:

What is difference between

int x=7; 

and

register int x=7; 

Almost certainly nothing.

register is a hint to the compiler that you plan on using x a lot, and that you think it should be placed in a register.

However, compilers are now far better at determining what values should be placed in registers than the average (or even expert) programmer is, so compilers just ignore the keyword, and do what they wants.

参考 http://stackoverflow.com/questions/3207018/register-keyword-in-c

和http://blog.linjian.org/articles/c-cpp-register-difference/

你可能感兴趣的:(c c++ register)