How to Use the Volatile Keyword in C++?
Last Updated :
19 Feb, 2024
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++
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
mutex mtx;
volatile int volVar = 0;
void incValue()
{
for ( int i = 0; i < 10; i++) {
mtx.lock();
volVar++;
mtx.unlock();
}
}
int main()
{
thread t1(incValue);
thread t2(incValue);
t1.join();
t2.join();
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)
Share your thoughts in the comments
Please Login to comment...