Keil Logo

volatile

The volatile type qualifier is used to restrict assumptions the compiler makes about object values. For example:

unsigned char reg1;   // Hardware Register #1
unsigned char reg2;   // Hardware Register #2

void func (void)
{
while (reg1 & 0x01)   // Repeat while bit 0 is set
  {
  reg2 = 0x00;        // Toggle bit 7
  reg2 = 0x80;
  }
}

This program uses two variables (reg1 and reg2) to access hardware registers. In most cases, the compiler loads reg1 into a register and does not re-read it between loop iterations (even though the hardware register may be changing). In addition, the three assignments to reg2 may simply be optimized to the final assignment (no code is generated for the first two assignments).

These effects are caused by the optimizer and are not bugs generated by the compiler. In fact, these are the types of optimizations the compiler should make. However, in this case they are certainly undesirable.

The volatile type qualifier was introduced to solve these types of problems. For example:

volatile unsigned char reg1;   // Hardware Register #1
volatile unsigned char reg2;   // Hardware Register #2

void func (void)
{
while (reg1 & 0x01)   // Repeat while bit 0 is set
  {
  reg2 = 0x00;        // Toggle bit 7
  reg2 = 0x80;
  }
}

By defining reg1 and reg2 as volatile, the compiler now knows that accesses to these variables may not be optimized out. The resulting code executes as desired.

  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.