If we declare a variable as volatile
every time the fresh value is updated
If we declare a variable as const
then the value of that variable will not be changed
Then const volatile int temp;
What is the use of declaring the variable temp
as above?
What happens if we declare as const int temp
?
An object marked as const volatile
will not be permitted to be changed by the code (an error will be raised due to the const
qualifier) - at least through that particular name/pointer.
The volatile
part of the qualifier means that the compiler cannot optimize or reorder access to the object.
In an embedded system, this is typically used to access hardware registers that can be read and are updated by the hardware, but make no sense to write to (or might be an error to write to).
An example might be the status register for a serial port. Various bits will indicate if a character is waiting to be read or if the transmit register is ready to accept a new character (ie., - it's empty). Each read of this status register could result in a different value depending on what else has occurred in the serial port hardware.
It makes no sense to write to the status register (depending on the particular hardware spec), but you need to make sure that each read of the register results in an actual read of the hardware - using a cached value from a previous read won't tell you about changes in the hardware state.
A quick example:
unsigned int const volatile *status_reg; // assume these are assigned to point to the
unsigned char const volatile *recv_reg; // correct hardware addresses
#define UART_CHAR_READY 0x00000001
int get_next_char()
{
while ((*status_reg & UART_CHAR_READY) == 0) {
// do nothing but spin
}
return *recv_reg;
}
If these pointers were not marked as being volatile
, a couple problems might occur:
*recv_reg
is changed by the loop, there's no reason it can't be read before entering the loop.The volatile
qualifiers ensures that these optimizations are not performed by the compiler.