A.6.2 Local Variables and Global Variables

Variables that can be used as local variables must be declared as local variables and not as global variables. There is a possibility that the value of a global variable will be changed by function calling or pointer operations, thus the efficiency of optimization is degraded.

The following advantages are available when local variables are used.

-

Access cost is low

-

May be assigned to a register

-

Efficiency of optimization is good

[Example]

Case in which global variables are used for temporary variables (before improvement) and case in which local variables are used (after improvement)

Source code before improvement

int tmp;
void func(int* a, int* b)
{
     tmp = *a;
     *a = *b;
     *b = tmp;
}

 

Assembly-language expansion code before improvement

__func:
     MOV.L #_tmp,R4
     MOV.L [R1],[R4]
     MOV.L [R2],[R1]
     MOV.L [R4],[R2]
     RTS

 

Source code after improvement

void func(int* a, int* b)
{
     int tmp;
     tmp = *a;
     *a = *b;
     *b = tmp;
}

 

Assembly-language expansion code after improvement

__func:
     MOV.L [R1],R5
     MOV.L [R2],[R1]
     MOV.L R5,[R2]
     RTS