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.
Best practices:
We can decleare a variable as volatile when there are possibility that the value of variable can be changed by system.
Rules:
volatile modifier can not be used with void, enum and function.
Advanced reader:
Most of time, memory mapped variable will be declared as volatile.
©2023-2024 rculock.com