Become a leader in the IoT community!
New DevHeads get a 320-point leaderboard boost when joining the DevHeads IoT Integration Community. In addition to learning and advising, active community leaders are rewarded with community recognition and free tech stuff. Start your Legendary Collaboration now!
Compilers do have the liberty to rearrange code how they see fit in order to produce optimal executables. Some of these changes related to volatile would be the compiler changing, for example, the order of access of a variable or caching the value of a variable such that for successive reads the value is only fetched for the first read and the cache is used for any subsequent read. Now this sounds neat but there are cases where it becomes undesirable. Imagine a register in your UART changes but the variable you used to track it is cached.
To avoid such nastiness, volatile is used to direct the compiler not to cache the values of the variable. It will generate code to take the value of the given volatile variable from the memory every time it encounters it. This mechanism is used because at any time the value can be modified by the OS or any interrupt. So using volatile will ensure accessing the value afresh every time.
Since you started can you break down volatile pointers and volatile values inside pointers, such as cases where one uses volatile twice.
Certainly.
1. So volatile values are used when the those values can change unexpectedly so we do not want the compiler to make any assumptions about the value of the variable.
“`volatile uint8_t counter = 0;
/// isr updates counter somewhere else
volatile int val = 0;
volatile *int volatile ptr = val;
“`
Intreasting, thank you
CONTRIBUTE TO THIS THREAD