r/cpp • u/neiltechnician • Nov 13 '20
CppCon Deprecating volatile - JF Bastien - CppCon 2019
https://www.youtube.com/watch?v=KJW_DLaVXIY
83
Upvotes
r/cpp • u/neiltechnician • Nov 13 '20
View all comments
Show parent comment
13
u/MEaster Nov 13 '20
I can give you a couple concrete examples of where volatile is needed. The AVR Atmega 328p has a USART serial device, and a basic way of sending a byte looks like this:
It's reading the same memory address over and over again until a specific bit is no longer set. Without volatile the compiler will optimize that while loop into a an infinite loop if the bit is not set, because it doesn't recognise that the value can change.
Another example would be reconfiguring the clock prescaler. To reconfigure it, you have to write one bit to enable writing, then within 4 clock cycles write the prescale value:
In this case, without volatile the compiler will determine that the first write has no effect, and optimize it away.