Skip to main content

Volatile variables in C

Volatile Variable

  • A volatile variable is a variable whose value can be changed by some external source, such as an interrupt handler, a hardware peripheral, or another concurrent process.

  • When a variable is declared as volatile, the compiler is instructed not to perform any optimizations that may affect the value of the variable, such as caching its value in a register or reordering code that accesses the variable.

Volatile Variable - Example

#include<stdio.h>

volatile int flag = 0;

void some_function()
{
while (flag == 0)
{
/* Wait for flag to be set */
}
/* Continue execution */
}

int main()
{
/* Set flag */
flag = 1;
return 0;
}

Explanation

  • The flag variable is declared as volatile.

  • This means that the compiler will not optimize the while loop that waits for the flag to be set, because the value of flag can be changed by some external source (main function).

info

Using volatile variables is important when writing code that interacts with hardware peripherals or runs in a multi-threaded environment, as it ensures that the compiler will not interfere with the correct operation of the program.