The definition form of register variable is:
Register type identifier variable name
Registers are closely related to machine hardware. Different types of computers have different numbers of registers, usually 2 to 3. For more than 2 to 3 register variables described in a function, the C compiler will automatically change the register variables into Automatic variable 。 Due to the limitation of hardware register length, the register variable can only be char, int or Pointer Type. The register specifier can only be used to describe the variables in the function and the Formal parameter , so it is not allowed to External variables or Static variable The description is“ register "。 register Type variables are often used as loops control variable This is the best occasion to use its high-speed features. Compare the operation speed of the following two programs. /*Procedure 1*/
main ( )
{register int temp, i;for ( i=0; i<=30000; i++ )for ( temp=0; temp<=100; temp++ ) ;printf ("ok\n");}
/*Procedure 2*/
#include <stdio.h>
int main( )
{int temp, i;for ( i=0; i<=30000; i++ )for ( temp=0; temp<=100; temp++ ) ;printf ("ok\n");}
In these two programs, the former uses two register variables, and the latter uses two Automatic variable The procedure is exactly the same except for this. But the execution speed is different at runtime. The former uses register variables faster than the latter uses automatic variables. (If in Turbo C Run program 2 in the environment of compiler The optimization option "use register variable" switch is OFF, otherwise, compiler The automatic optimization program uses registers, and both programs will get the same result.) Because the register variable uses hardware CPU In register , the register variable has no address, so the address operator "&" cannot be used to find the address of the register variable.