How to Use the Volatile Keyword in C++? Last Updated : 19 Feb, 2024 Comments Improve Suggest changes 8 Likes Like Report In C++, the volatile keyword is used to tell the compiler that the value of the variable declared using volatile may change at any time. In this article, we will learn how to use the volatile keyword in C++. Volatile Keyword in C++We can use the volatile keyword for different purposes like declaring some global variables, variables across shared threads, etc. Syntax to use Volatile Keyword in C++volatile dataType varName;C++ Program to Show the Use of Volatile Keyword C++ // C++ Program to Show how to use the Volatile Keyword #include <iostream> #include <mutex> #include <thread> using namespace std; // Mutex for synchronization mutex mtx; // Volatile variable to be accessed by multiple threads volatile int volVar = 0; // Function to increment the volatile variable void incValue() { for (int i = 0; i < 10; i++) { mtx.lock(); // Lock the mutex before accessing // volVar volVar++; mtx.unlock(); // Unlock the mutex after modifying // volVar } } int main() { // Create two threads to increment volVar thread t1(incValue); thread t2(incValue); // Wait for both threads to finish t1.join(); t2.join(); // Output the final value of volVar cout << "Final value of volVar: " << volVar << endl; return 0; } Output Final value of volVar: 20 Time Complexity: O(1), for each lock and unlock operation.Auxiliary Space: O(1) Create Quiz Comment P pradeep1210 Follow 8 Improve P pradeep1210 Follow 8 Improve Article Tags : C++ Programs C++ CPP Examples Explore C++ BasicsIntroduction to C++3 min readData Types in C++6 min readVariables in C++4 min readOperators in C++9 min readBasic Input / Output in C++3 min readControl flow statements in Programming15+ min readLoops in C++7 min readFunctions in C++8 min readArrays in C++8 min readCore ConceptsPointers and References in C++5 min readnew and delete Operators in C++ For Dynamic Memory5 min readTemplates in C++8 min readStructures, Unions and Enumerations in C++3 min readException Handling in C++12 min readFile Handling in C++8 min readMultithreading in C++8 min readNamespace in C++5 min readOOP in C++Object Oriented Programming in C++8 min readInheritance in C++6 min readPolymorphism in C++5 min readEncapsulation in C++3 min readAbstraction in C++4 min readStandard Template Library(STL)Standard Template Library (STL) in C++3 min readContainers in C++ STL2 min readIterators in C++ STL10 min readC++ STL Algorithm Library3 min readPractice & ProblemsC++ Interview Questions and Answers1 min readC++ Programming Examples4 min read Like