The volatile keyword tells the computer that a variable can change at any time, even if the program does not change it. This helps the program always get the latest value.
0
0
Volatile keyword and why it matters in Embedded C
Introduction
Reading a hardware sensor value that can change anytime.
Working with variables shared between main code and interrupt handlers.
Accessing memory-mapped device registers that update independently.
Using flags that can be changed by other parts of the program or hardware.
Syntax
Embedded C
volatile type variable_name;volatile is placed before the variable type.
It tells the compiler not to optimize or cache the variable value.
Examples
This declares an integer variable
sensor_value that can change anytime.Embedded C
volatile int sensor_value;This declares a character variable
flag that may be changed outside normal program flow.Embedded C
volatile char flag;
Sample Program
This program shows a volatile variable counter that can be changed by an interrupt handler. The main program prints the value before and after the interrupt changes it.
Embedded C
#include <stdio.h> volatile int counter = 0; void interrupt_handler() { // This simulates an interrupt changing the counter counter++; } int main() { printf("Counter before interrupt: %d\n", counter); interrupt_handler(); printf("Counter after interrupt: %d\n", counter); return 0; }
OutputSuccess
Important Notes
Without volatile, the compiler might assume the variable never changes and keep an old value.
Use volatile only when needed, because it can slow down the program.
Summary
volatile tells the program a variable can change anytime.
It is important for hardware and interrupt-related variables.
It prevents the compiler from optimizing away important updates.