Const and volatile in C/C++

Const and volatile keyword IN C /C++

Before we take an example we learn about Const and volatile Keyword. There are Type of Qualifiers in c++ Const and volatile. In C/C++ when we declare the variable with const keyword then we cannot change its value. A const variable must be assigned a value at the time of its declaration. But on the other hand declaration with volatile keyword we tell to complier that some one change this value inside or outside the program.
These two keyword related with optimizations process. When we declear an variable with volatile basically we says don't perform any optimizations on operations on this memory because something else outside the program may change it.
For Example
const int x=10;
or
const char name [20] ="LEARNING";
You can also declear an pointer, function, and class as const.
For example:
const int x=10; // x as an variable which assign value 10 and can not modify
int y=20; //y is an ordinary varaible and we can mdify it any time any where.

Detail Example:



void main(void)

 {

int const x = 10;

while(x == 10)

{ //your code

 }

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of x, so it may be tempted to optimize the while loop by changing it from while (x== 100) to simply while(true) so that the execution could be fast (since the condition in while loop appears to be true always).
Now we take an other example


void main(void)

 {

int volatile  x = 10;

while(x == 10)

{ //your code

 }


Its means we says to complier that x is volatile in nature and it can be changed by some else . So don't optimize its. if the compiler doesn't optimize it, then it has to fetch the value of x and compare it with 10, each time which obviously is a little bit slow.