The volatile Keyword

Get a detailed introduction to the 'volatile' keyword.

We'll cover the following

Proposal

The abstract in the proposal P1152R0 gives a short description of the changes that volatile undergoes:

“The proposed deprecation preserves the useful parts of volatile and removes the dubious / already broken ones. This paper aims at breaking at compile-time code which is today subtly broken at run time or through a compiler update.”

Before I dive into volatile, I want to answer the crucial question: When should you use volatile? A note from the C++ standard says that “volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.”

This means that for a single thread of execution, the compiler must perform load or store operations in the executable as often as they occur in the source code. volatile operations, therefore, cannot be eliminated or reordered. Consequently, you can use volatile objects for communication with a signal handler but not for communication with another thread of execution.

Deprecated features

Now, I want to talk about the deprecated features:

  1. Deprecate volatile compound assignment, and pre/post increment/decrement

  2. Deprecate volatile qualification of function parameters or return types

  3. Deprecate volatile qualifiers in a structured binding declaration

If you want to know all the sophisticated details, I strongly suggest you watch the CppCon 2019 talk “Deprecating volatile” from JF Bastien. Here are a few examples from his talk.

Additionally, I fixed a few typos in the source code. The numbers in the bullets refer to the three deprecations listed earlier.

  • 1:
    int neck, tail;
    volatile int brachiosaur;
    brachiosaur = neck;       // OK, a volatile 
    store tail = brachiosaur; // OK, a volatile load
    
    // deprecated: does this access brachiosaur once or twice
    tail = brachiosaur = neck;
    
    // deprecated: does this access brachiosaur once or twice
    brachiosaur += neck;
    
    // OK, a volatile load, an addition, a volatile store
    brachiosaur = brachiosaur + neck;
    

Get hands-on with 1200+ tech skills courses.