C volatile keyword

The volatile keyword prevent the compiler from applying any optimizations on objects. The system always reads the current value of a volatile object from the memory location rather than keeping it's value in a temporary register at the point it is requested.

Considering this case[1]. In most cases, the compiler loads reg1 into a register and not re-read it between loop iteration. Even the hardware register is changing. Second, the two statements by assigning reg2, the compiler will optimized these two statements into a optimized one.

unsigned char reg1;
unsigned char reg2;

void func(void) {
	while (reg1 & 0x01) { // reg1 is read into register from memory location
		reg2 = 0x00;
		reg2 = 0x80;
	}
}

As a result, the volatile qualifier is introduced to solve these types of problems.

volatile unsigned char reg1;
volatile unsigned char reg2;

void func(void) {
	while (reg1 & 0x01) { // reg1 is read from memory location
		reg2 = 0x00;
		reg2 = 0x80;
	}
}

When to use Volatile Keyword

Here are some cases to use volatile[2]

An example to declare a memory mapped register accessing

volatile char *ptr = (volatile char *)0x200000;
printf("value of register is 0x%x\n", *ptr);


  1. https://developer.arm.com/documentation/101655/0961/Cx51-User-s-Guide/Language-Extensions/Type-Qualifiers/volatile ↩︎

  2. https://www.embedded.com/introduction-to-the-volatile-keyword/ ↩︎