Summary: In this tutorial, we will learn what the volatile keyword is and when we should use it in our C++ code.

What is Volatile in C++?

The volatile keyword in C++ is a type qualifier used to declare that a variable or object can be modified in a program by something like the operating system, hardware, or any other entity which is outside of the program.

It is used to prevent the compiler from optimizing the code that may seem to it as unchangeable.

Example:

Consider the following C++ snippet for instance:

int num = 10

while(num==10){
   cout << num;
}

The compiler sees that throughout the program the value of num is not changing, so is the condition num == 10.

Because the while loop condition is always true in the above code, the compiler may tempt to optimize the while loop by changing it from while(num==10) to something which is equivalent to while(true), otherwise, in every iteration, it has to fetch the value of num and compare it with integer 10, which is definitely slower.

However, sometimes we do not want this optimization to happen because we may have designed it in such a way that something else is modifying the value of the integer num (outside of the program) which the compiler is not aware of.

So, to ensure that the compiler doesn’t optimize the while loop, we use the volatile keyword during variable or object declaration.

Important Points About Volatile in C++

The volatile keyword is a hint to the compiler to avoid aggressive optimization involving the variable or object.

Because volatile is a qualifier, we can also use it on the methods. In that case, those methods can only be called on the volatile instances.

Reference: StackOverflow

Leave a Reply