I read about the volatile keyword, but I don’t know in what situations I should use it.
Is it when the memory (variable) is getting updated and the process is not aware of that?
In what cases should drivers use ‘volatile’ variables?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The most common case in my world is when you are programming microcontrollers that use memory-mapped I/O. The value in a register could change due to external digital inputs, but if you don’t declare a variable as
volatile, the compiler might optimize the code out completely and you’ll be wondering why nothing works.Matt suggested that I embellish on the statement regarding code getting “optimized out”. Memory mapped I/O is accessed in code via pointers. When you want to check the state of a button, you will typically bitwise AND the value of the register with the bitmask for the button. If you don’t specify volatile, the compiler will say, “hey, your code never actually changes the value of that pointer, so I’m going to just remove that statement where you’ve bitwise ANDed it, because the value is always the same!”.
Hopefully this clears my statement up a bit. Thanks for the suggestion, Matt.