const means the program can not modify the value volatile means the value may be arbitrarily modified outside the program.
the two are separate and not mutually exclusive.
use them together, for instance, in the case of reading a hardware status register. const prevents the value from being stomped on, while volatile tells the compiler that this value can be changed at any time external to the program.
this const volatile <type> <variablename> will thus satisfy both requirements and prevent an optimizing compiler from incorrectly optimizing the code, that it would do if only "const" were used.
i want to know what is the use of const volatile variable, where exactly it is required to use.
Let's take an example
const volatile usigned int *REG_A = (usigned int *) init_hardware_n_return_address of REG_A();
In the above snippet function "init_hardware_n_return_address of REG_A()" modifies the content of the REG_A( register A say) of a peripheral device , say after initiatialising it ( which cause the content of R/W register REG_A modified by peripheral itself) and returns the address of REG_A to the program .
The assignment in the above snippet implies here that content of REG_A can be modifiable only be external sources like peripheral hardware itself and and your code is not supposed to modify the content of REG_A .
Also whenever such variable is encountered compiler should "load " it value every time instead of doing any code optimasation
Typically memory mapped variables are one consumers for such usage
Declaring a variable as const indicates the compiler that the variable will never be changed(either by the program/external entity like a peripheral device.
Declaring a variable as volatile indicates the compiler that the variable might be changed dynamically (by an external entity or by our program). Hence whenever we are accessing that variable, compiler will not perform optimization and will fetch the value from its address(which will cost us a few more cpu cycles).
Now Declaring a variable as a const volatile, we indicate the compiler that variable cant be modified by the program but can be modified by an external entity.
The usage of const volatile is more predominant in Device Driver Programming.