Check The Programming Section
The const keyword, in C/C++ is used to create a variable of type constant, whose value can not be changed by the program. Most importantly a const variable must be initialized at the time of declaration. eThe declaration of a const variable can be as follows:
const type variableName = value;
Here, type can be anything from data types. Most importantly, the use of assignment operator in const declaration is required, if we want to give an initial value. Thereafter, use of assignment operator to update the value of a const variable is illegal.
variableName = anyValue; //will be an error.
Let’s declare a const int variable
const int num = 90;
We can also placed the const modifier after the type name, as follows:
int const num = 90;
Note: Due to the use of const modifier the compiler is free to place num in a read-only memory (ROM).
Throughout this tutorial we will see the various ways of using the const qualifier. For now, we are limited its use with a creation of const variable only.
C'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. Syntax to use volatile:
volatile int num;
We can also mixed with other modifiers as follows:
volatile unsigned int k;
Normally, if we do not want to use a variable very frequently then volatile can be one of the options. The volatile keyword tells the compiler that the variable must be stored in memory and must be accessed from the memory. It is always read from the memory, used/modified and then stored back there, it is never cached in CPU or registers.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
The modifier volatile also tells the compiler that a variable's value may be changed in ways not explicitly specified by the program, using an assignment operator.
For example, a global variable's address may be passed to the operating system's clock routine and used to hold the real time of the system. In this situation, the contents of the variable are altered without any explicit assignment statements in the program. This is important because most C/C++ compilers automatically optimize certain expressions by assuming that a variable's content is unchanging if it does not occur on the left side of an assignment statement; thus, it might not be reexamined each time it is referenced.
Also, some compilers change the order of evaluation of an expression during the compilation process. The volatile modifier prevents these changes.
The Complete Reference, C++, 4th Edition, Hebert Schieldt