Declaring a Variable as Volatile in C

In C, the volatile keyword is used to declare a variable whose value can be changed unexpectedly at any time, often outside the control of the program. The volatile qualifier informs the compiler that it should not optimize code that deals with this variable, as its value may be modified by external factors such as hardware, interrupt service routines, or other concurrently executing threads.

Syntax for Declaring a Volatile Variable


volatile data_type variable_name;
Here:

Why Use the volatile Keyword?

1: Using a Volatile Variable


#include <stdio.h>
volatile int flag = 0; // Declare flag as volatile
void interrupt_handler() {
    flag = 1; // Simulate an interrupt
}
int main() {
    while (flag == 0); // Wait for the flag to change
    printf("Interrupt occurred!\n");
    return 0;
}

Output

Interrupt occurred!

Explanation of the Code

In this example:

Practical Use Cases of Volatile Variables

2: Using Volatile for Hardware Registers


#include <stdio.h>
#define STATUS_REGISTER (*(volatile unsigned char *)0x4000)
int main() {
    while (STATUS_REGISTER != 0xFF) {
        // Wait for the hardware status register to be ready
    }
    printf("Hardware is ready!\n");
    return 0;
}

Output

Hardware is ready!

Points to Remember

Difference Between volatile and const

Aspect volatile Keyword const Keyword
Purpose Indicates that a variable's value may change unexpectedly Indicates that a variable's value cannot be modified after initialization
Usage Used for hardware registers, interrupt flags, shared variables Used for defining constants like PI, array sizes, etc.
Memory Read Always reads from memory May use stored value from cache (if not volatile)
Compile-Time Error Prevents optimization but allows value modification Prevents any modification after initialization

The volatile keyword is a powerful tool in C for handling variables that may change unpredictably due to hardware, interrupts, or concurrent threads. By informing the compiler not to optimize access to these variables, you can ensure that your program always uses the latest value, which is crucial in embedded systems and low-level programming.