本文转自class="tags" href="/tags/BaiDu.html" title=百度>百度百科
在程序运行时c;根据需要到内存中相应的coration:underline; color:rgb(255,0,0); font-weight:bold">class="tags" href="/tags/CunChu.html" title=存储>存储单元中调用c;如果一个变量在程序中频繁使用c;例如循环变量c;那么c;系统就必须多次访问内存中的该单元c;影响程序的执行效率。因此c;C\C++class="tags" href="/tags/YuYan.html" title=语言>语言还定义了一种变量c;color:rgb(204,0,0); font-weight:bold">不是保存在内存上c;而是直接class="tags" href="/tags/CunChu.html" title=存储>存储在CPU中的寄存器中c;这种变量称为寄存器变量。 寄存器变量的定义形式是: register 类型标识符 变量名 color:rgb(204,0,0); font-weight:bold">寄存器是与机器硬件密切相关的c;不同类型的计算机c;寄存器的数目是不一样的c;通常为2到3个c;对于在一个函数中说明的多于2到3个的寄存器变量c;C编译程序会自动地将寄存器变量变为自动变量。 color:rgb(255,0,0); font-weight:bold"> 由于受硬件寄存器长度的限制c;所以寄存器变量只能是char、int或指针型。寄存器说明符只能用于说明函数中的变量和函数中的形参c;因此不允许将外部变量或静态变量说明为"register"。 color:rgb(204,0,0); font-weight:bold"> register型变量常用于作为循环控制变量c;这是使用它的高速特点的最佳场合。比较下面两个程序的运算速度。
/* 程序1 */
main ( )
{
register int temp, i;
for ( i=0; i<=30000; i++ )
for ( temp=0; temp<=100; temp++ ) ;
printf ("ok\n"); }
/* 程序2 */
#include <stdio.h>
main( )
{ int temp, i;
for ( i=0; i<=30000; i++ )
for ( temp=0; temp<=100; temp++ ) ;
printf ("ok\n"); }
这两个程序中c;前者使用了两个寄存器变量c;后者使用了两个自动变量程序除此之外完全一样。
但运行时感觉的执行速度是不同的c;前者color:rgb(204,0,0); font-weight:bold">使用寄存器变量的程序要比后者使用自动变量的程序要快。
(color:rgb(204,0,0); font-weight:bold">如果在tubro 2的环境下运行程序2c;则应该将class="tags" href="/tags/BianYiQi.html" title=编译器>编译器class="tags" href="/tags/YouHua.html" title=优化>优化选项"use register variable"开关关上(OFF)
color:rgb(204,0,0); font-weight:bold">c;否则c;class="tags" href="/tags/BianYiQi.html" title=编译器>编译器自动class="tags" href="/tags/YouHua.html" title=优化>优化程序使用寄存器c;两个程序会得到相同的结果。)
color:rgb(204,0,0); font-weight:bold">由于register变量使用的是硬件CPU中的寄存器c;寄存器变量无地址c;所以不能使用取地址运算符"&"求寄存器变量的地址。