According to this defect report C++03 Standard does not guarantee that in the following code:
volatile int x;
void f() {
x;
}
the variable is read from.
Then how do I write code that just read the volatile variable value and discards the result (read for the sake of read)?
Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time-without any action being taken by the code the compiler finds nearby. The implications of this are quite serious.
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
The volatile qualifier declares a data object that can have its value changed in ways outside the control or detection of the compiler (such as a variable updated by the system clock or by another program).
Volatile Keyword means that the variable will be loaded from its memory location every time you are using this variable, the compiler will never depend on the temporary value stored in the internal CPU Registers.
int i = x;
should work. This code absolutely requires reading the volatile variable and the optimizer is not allowed to optimize the read away. But since the variable i
is unused the optimizer can avoid any extra work involved in storing the read value.
You might also need something like this to avoid compiler warnings: (void)i;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With