News:

PROTON pic BASIC Compilers for PIC, PIC24, dsPIC33

Main Menu

"C" volatile declaration - am I missing something

Started by RGV250, Jun 12, 2023, 10:50 PM

Previous topic - Next topic

RGV250

Hi,
I am looking at some C code and came across "volatile" used in a lot of places before declaring the variables.
I looked it up and found this.
QuoteC's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.
Surely that is just a variable, why do you need to tell the compiler as that is the whole point of using a variable rather than a constant.
Is this just a case of the people who wrote the C compiler being on drugs or something as I see no point in it at all.

Bob

tumbleweed

It doesn't have to do with it being a 'variable' or 'constant'. It has more to do with code generation and optimizations.

Say you have a variable that's never changed. The compiler is free to optimize it away, to the point of it never even allocating storage for it.

Or, say that the variable doesn't change value over a few statements. The compiler can see that, and may keep the variable in a register or something and not reload it from memory.

Now say that variable value is changed outside the current context, like in an ISR. The compiler wouldn't know about that, so it wouldn't know that the value has changed and it needs to reload it from memory.

Declaring a variable 'volatile' tells the compiler not to make any assumptions about the variable's usage, effectively saying to the compiler "this variable may change at any time without your knowledge".


RGV250

Hi Tumbleweed,
Thanks for the explanation, I am assuming this is a legacy thing that is not really relevant as Positron does not have this facility. I am pretty sure if it were important Les would have implemented it.

Bob

John Lawton

If you are using the Positron Studio IDE, it issues a warning if it finds unused variables in your source code.
I like Positron precisely because it isn't too clever and doesn't do things like removing 'unused' variables, so the human programmer is still in control.