Constant-Variable Optimization

If a constant non-volatile variable is used in any expression, the Compiler replaces it by the constant value it holds. This needs less code than taking the object itself.

The constant non-volatile object itself is removed if there is no expression taking the address of it (take note of ci in the following listing). This results in using less memory space.

Listing: Example demonstrating constant-variable optimization


void f(void) {

  const int ci  = 100; // ci removed (no address taken)

  const int ci2 = 200; // ci2 not removed (address taken below)

  const volatile int ci3 = 300; // ci3 not removed (volatile)

  int i;

  int *p;

  i = ci;   // replaced by i = 100;

  i = ci2;  // no replacement

  p = &ci2; // address taken

}

Global constant non-volatile variables are not removed. Their use in expressions are replaced by the constant value they hold.

Constant non-volatile arrays are also optimized (take note of array[] in the following listing).

Listing: Example demonstrating the optimization of a constant, non-volatile array


void g(void) {

  const int array[] = {1,2,3,4};

  int i;

  i = array[2]; // replaced by i=3;

}