I know that by the volatile keyword,
volatile int k=7;
we hint the compiler that the variable can be changed at any time but what about a simple
int k=7? Can we change it at any time because it is not constant? What is different?
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.
It’s used in low level programming with interrupts and so on mostly
if you don’t declare the variable as volatile the compiler will probably notice that count can’t change in the while loop and so won’t bother to actually read the value every time from memory so it will never exit the loop.
If you declare it volatile then the compiler will read the value from memory every time as you’ve told it that the value might change without notice…
Another use is to map hardware ports.
On a microcontroller you might have some digital inputs which “appear” at a certain memory address. You can read them as if they were a variable but of course the value will potentially change all the time depending on the input signals. Declaring the value as volatile will indicate to the compiler that yes you actually do need to read this memory location every single time because it might have changed, and no you can’t assume that it won’t change unless you change it.
Unless you are using low level interrupts or some uses of threading then you don’t need to use it.
EDIT: To be clear, volatile is NOT for synchronization between theads in standard c++, it only does a part of what is necessary. The last sentence in my original post could be misleading. The examples and stuff about hardware interrupts etc in my post are what volatile is for, it absolutely ISN’T for threading and don’t even try to use it for that.
I originally wrote “some uses of threading” because on some platforms it might be sufficient to use volatile. This is BAD ADVICE in general but if you have a single core and all writes are visible to all “threads” then it might work for you. For example on a microcontroller with a simple interrupt based thread switching system it would likely “work” even though not guarenteed by the standard. But don’t do it. In general it’s just wrong, and c++11 has ways that actually work (remember this answer was written pre c++11)