const
means that the variable cannot be modified by the c code, not that it cannot change. It means that no instruction can write to the variable, but its value might still change.
volatile
means that the variable may change at any time and thus no cached values might be used; each access to the variable has to be executed to its memory address.
Since the question is tagged "embedded" and supposing temp
is a user declared variable, not a hardware-related register (since these are usually handled in a separate .h file), consider:
An embedded processor which has both volatile read-write data memory (RAM) and non-volatile read-only data memory, for example FLASH memory in von-Neumann architecture, where data and program space share a common data and address bus.
If you declare const temp
to have a value (at least if different from 0), the compiler will assign the variable to an address in FLASH space, because even if it were assigned to a RAM address, it still needs FLASH memory to store the initial value of the variable, making the RAM address a waste of space since all operations are read-only.
In consequence:
int temp;
is a variable stored in RAM, initialized to 0 at startup (cstart), cached values may be used.
const int temp;
is a variable stored in (read-ony)FLASH, initialized to 0 at compiler time, cached values may be used.
volatile int temp;
is a variable stored in RAM, initialized to 0 at startup (cstart), cached values will NOT be used.
const volatile int temp;
is a variable stored in (read-ony)FLASH, initialized to 0 at compiler time, cached values will NOT be used
Here comes the usefull part:
Nowadays most Embedded processors have the ability to make changes to their read-only non-volatile memory by means of a special function module, in which case const int temp
can be changed at runtime, altought not directly. Said in another way, a function may modify the value at the address where temp
is stored.
A practical example would be to use temp
for the device serial number. The first time the embedded processor runs, temp
will be equal to 0 (or the declared value) and a function can use this fact to run a test during production and if sucessfull, ask to be assigned a serial number and modify the value of temp
by means of a special function. Some processors have a special address range with OTP (one-time programmable) memory just for that.
But here comes the difference:
If const int temp
is a modifiable ID instead of a one-time-programmable serial number and is NOT declared volatile
, a cached value might be used untill the next boot, meaning the new ID might not be valid untill the next reboot, or even worse, some functions might use the new value while other might use an older cached value untill reboot.
If const int temp
IS declared voltaile
, the ID change will take effect immediately.