Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a C++03 compliant way of fetching a value from a volatile variable?

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)?

like image 590
sharptooth Avatar asked Dec 19 '12 10:12

sharptooth


People also ask

What is a volatile variable in C?

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.

How is the value of volatile variables altered?

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.

What is volatile type qualifier in C?

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).

Where volatile variables are stored in C?

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.


1 Answers

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;

like image 96
bames53 Avatar answered Sep 28 '22 06:09

bames53