volatile
volatile is an modifier of data type in c.
Syntax
volatile data_type var_name;
Declearation of volatile variable
volatile int data;
Properties of register variable:
- A volatile variable is a variable that can change unexpectedly. The volatile keyword is intended to prevent the compiler from applying any optimizations on the variable.
- A volatile variable value can be changed by the background routine/callback of system. the background routine can be interrupt status, timer, GPIO indications, etc.
- Variables declared as volatile are not cached, so compiler should not reuse the value already loaded in a register, but access the memory again as the value in register is not guaranteed to be the same as the value stored in memory.
- Volatile variable will take more execution time beacuse everytime we need to read it from memory.
We can decleare a variable as volatile when there are possibility that the value of variable can be changed by system.
volatile modifier can not be used with void, enum and function.
The volatile keyword is a compiler directive, not a cache control mechanism. It instructs the compiler to avoid optimizing accesses to the variable—meaning it must not cache the value in a register or eliminate seemingly redundant reads/writes. Instead, every access must go directly to memory.
However, volatile does not disable CPU caching or enforce cache coherence. CPU caches (L1/L2/L3) are managed by hardware and operate independently of the compiler. The compiler has no direct control over them unless explicitly coordinated through mechanisms like memory barriers or MMU settings.
Even if a variable is declared volatile, the CPU may still cache the memory address if it's marked as cacheable. In embedded systems, hardware registers that are memory-mapped and designated as non-cacheable (e.g., using "device memory" attributes in the MMU/MPU) bypass CPU caches—but this is determined by hardware configuration, not by the volatile qualifier in software.
©2023-2024 rculock.com