volatile Qualifier in C++
In C++, the volatile qualifier is used to mark variables that might change unexpectedly, often due to external factors like hardware interactions. This keyword can be applied to variables, as well as to structures and unions to ensure that their member variables are treated as volatile. When we declare a variable as volatile, the compiler is instructed not to optimize code involving this variable to ensure that every access to the variable is directly to its actual memory location, preventing the compiler from caching the variable in registers or removing seemingly redundant accesses.
Syntax of volatile in C++
volatile dataType variableName;
Example
The below example demonstrates how we can use volatile qualifiers in C++.
// C++ program to demonstrate the use of volatile qualifier
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
// Declaring y as a volatile integer to ensure changes are
// noticed by all threads.
volatile int y = 0;
// Function to change the value of y after a delay.
void changeY()
{
// Pause the program execution for 1 second.
this_thread::sleep_for(std::chrono::seconds(1));
// Change the value of y.
y = 20;
}
int main()
{
// Create a new thread that runs the changeY function.
thread t(changeY);
// Busy-wait loop that exits when y changes.
while (y == 0) {
}
// Print the updated value of y.
cout << "Value of y: " << y << endl;
// Wait for the thread t to finish.
t.join();
return 0;
}
Output
Value of y: 20
Type Qualifiers in C++
In C++, type qualifiers are keywords that modify the properties of data types, influencing how variables, pointers, or references can be used. These qualifiers enhance variable declarations by providing additional information on their access and usage constraints, ensuring more controlled and secure code behavior. In C++ common type qualifiers include: const, volatile, and mutable, each serving to specify particular attributes or constraints for handling variables and memory.
Contact Us