What is the volatile keyword in C?

volatile tells the compiler that the value of a variable can change at any time, from outside the normal program flow. So the compiler must read it from memory each time, and cannot keep it in a register.

volatile int flag = 0;      // may be changed by an interrupt or another thread

while (flag == 0) {
    // wait
}

Without volatile the compiler may see that the loop never changes flag and turn it into an infinite loop. It is used for hardware registers, interrupt handlers and signal flags. It does not make the code thread safe.


Learn more about the similar topics:
Tutorials
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?