What is the significance of the "volatile" key word with respect to Embedded Systems?

Let's have a look at an example. When you look at C header files for PIC microcontrollers, you will see that many elements are declared volatile:

extern volatile unsigned char           PORTB               @ 0x006;

As you have read, the volatile keyword disables compiler optimization. Suppose you write a program that does the following:

PORTB = 0x00;            // set all of port B low
while (PORTB == 0x00);   // wait for any pin to get high
// do something else

When the compiler optimises this code, it will recognise the second line as an infinite loop: the condition is true and never gets false within its body. Therefore, everything after the infinite loop does not need to be compiled as it will never be ran. Hence, the compiler may decide to not include that part of the code in the generated assembly code.

However, this PORTB is actually linked to a physical port. It is a hardware port whose value may be altered by the external circuitry. This means that although the loop seems to be infinite, it doesn't have to be. The compiler can't possibly know this.

That's where volatile comes in. When PORTB is declared volatile, the compiler won't do any optimisation based on reasoning about PORTB. It will assume that its value may be changed at any time by external factors.


In the embedded systems world, one of the key aspects of the volatile key-word is that it denotes a variable that may change at any time (eg an external/hardware data input - eg an ADC) and therefore the compiler must not optimise use.

But specifically, when used with a control register, it indicates that a read access may in fact change the data!

As a general rule of thumb, I would recommend the use of the volatile qualifier in all of the following:

  • All hardware register accesses(read and write)
  • All variables that are accessible in multiple threads (especially interrupt handlers)

Note: accessing a volatile is not necessarily atomic, so it is imperative that you know your hardware and your code structure.


The volatile keyword is primarily used tell the compiler the value of the variable may change anytime. It also tells the compiler the not to apply optimization on the variable. I am not too much of an expert on this but below is good reference that I have referred in the past.

volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby. The implications of this are quite serious. However, before we examine them, let's take a look at the syntax.

Reference:

  • Introduction to the volatile keyword

Tags:

C

Embedded