DEV Community

Professor Himtee
Professor Himtee

Posted on

3

volatile vs const in cpp

volatile and const keywords are very confusing from there implementation perspective. Today we will see the basic fundamental difference between the two.
const is pretty straight forward, we will declare a variable const if the value of the variable is not changing during the runtime of the program. It helps in fast execution of the program as compiler caches the value in the cache memory of the CPU.
Eg:
void foo()
{
const int a = 100;
}

Whereas the purpose of volatile is different, when you declare any variable with volatile keyword compiler will not perform any kind of optimization for that variable. The optimization is not done because the value for that variable may change by some external factors which compiler can't detect at runtime.
Eg:
void foo()
{
volatile int a = 100;
while(a)
{
//operation
}
}

In the above example the execution condition of the while loop is constant, if the value of a is not changing inside the loop. Then compiler will try to optimize this conditional statement inorder to minimize the data fetching overhead for the CPU. It will try to replace the above code with something like below.

void foo()
{
volatile int a = 100;
while(1)
{
//code
}
}

But imagine the senario when the value of a is getting changed by some external factors like threading, hardware register of the CPU or by some other means. Then it will end up on giving us some garbage value or even leads to crashing of the program.
So, it's always advisable to use volatile very carefully.

To read more about volatile keyword refer this,
https://en.wikipedia.org/wiki/Volatile_(computer_programming)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay