Sobes.tech
Senior

What is the purpose of the volatile keyword?

sobes.tech AI

Answer from AI

The keyword volatile in programming languages (e.g., C/C++) is used to tell the compiler that the value of a variable may change outside the control of the program, such as by hardware or another thread.

This is important in embedded systems and IoT, where variables may reflect the state of hardware registers or be shared between interrupts and main code.

Without volatile, the compiler might optimize the code assuming the variable's value does not change on its own, which can lead to errors.

Example:

volatile int sensor_value;

void ISR() { // interrupt handler
    sensor_value = read_sensor();
}

int main() {
    while(1) {
        if(sensor_value > threshold) {
            // react to change
        }
    }
}

Here, volatile ensures that each time sensor_value is accessed, the current value is read from memory rather than using a cached value.

What is the purpose of the volatile keyword… - sobes.tech