C++ Volatile Keyword

Volatile keyword can be specified for any C++ variable in order to tell the compiler that the variable should not be optimized. I'll show you what this means and why this Computer Engineering secret is very rare to find in any code. It's used in multi-threaded code or embedded system designs.

Take this code for example:

volatile int importantCheck;

void InterruptOrThread(){
  importantCheck = 5;
}

void main(){
  importantCheck = 0;
  CreateThread();
  ExecuteActions();
  DoEvents();
  if(importantCheck == 5){
    LaunchProgram();
  }
}

If we did not have the volatile keyword on importantCheck integer, then the compiler will optimize this code, because the InterruptOrThread() function isn't called directly by the main thread, but it is called as a thread or an interrupt in an embedded system.

Volatile means that the C++ variable should not be optimized.

The compiler will remove the check "importantCheck == 5" and it will remove the LaunchProgram() function, because the compiler believes that it's a mistake and that importantCheck will never be 5, so it removes it.

Volatile is used in multi-threaded or interrupt driven programs because the compiler shouldn't optimize all variables because compilers cannot understand threads very well.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.