Volatile Variables
(ISO C, §6.7.3) When you declare a volatile variable, the Carbide C compiler takes the following precautions to respect the value of the variable:
- The compiler stores commonly used variables in processor registers to produce faster object code. However, the compiler never stores the value of a volatile variable in a processor register.
- The compiler uses its common sub-expression optimization to compute the addresses of commonly used variables and the results of often-used expressions once at the beginning of a function to produce faster object code. However, every time an expression uses a volatile variable, the compiler computes both the address of the volatile variable and the results of the expression that uses it.
Listing 1 shows an example of volatile variables.
Listing 1. Volatile Variables
void main(void)
{
int i[100];
volatile int a, b; /* a and b are not cached in registers. */
a = 5;
b = 20;
i[a + b] = 15; /* compiler calculates a + b */
i[a + b] = 30; /* compiler recalculates a + b */
}
The compiler does not place the value of a, b, or a+b in registers. But it does recalculate a+b in both assignment statements.