32bitSaviour
DIIDevHeads IoT Integration Server
•Created by Afuevu on 12/21/2024 in #code-review
Struggled with a Bug on My Energy Meter Project
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.
5 replies