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?
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?
volatile prevents compiler optimizations and tells the compiler that the contents of the variable declared volatile can change at any time (i.e. a hardware device, interrupt, or another thread kicks in and writes into the variable's memory location). This means, caching values in CPU registers is not possible.
volatile int a = foo();
d=a+4;
e=a+4;
f=a+4;
Here, the compiler is forced to read a from memory every time it is used. If there was no volatile, precomputing a+4 would be a valid (and effective) optimization.
volatile int a = 4;
return a+5;
Here, the compiler is not allowed to optimize this to a simple return 9; because the contents of a might change between initialization (line 1) and first use (line 2);
Each time the compiler comes across an access to k, it will refetch it from memory instead of optimizing the code to collapse multiple uses of it.
int k = 7;
int i = k;
int j = k;
becomes equivalent to:
int k = 7;
int i;
int j;
i = j = k;
but
volatile int k = 7;
int i = k;
int j = k;
does not.
Volatile forces the variable to be read from memory each time instead of caching it.
It's used in low level programming with interrupts and so on mostly
volatile int count;
void test()
{
while(count< 100)
{
// do nothing
}
}
//
// Interrupt function called by the hardware automatically at intervals
//
void interrupt()
{
count = count + 1;
}
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.