Why is it dangerous to get rid of volatile?
c++, volatile
Solution
Not only can the compiler optimize away access to non-volatile variables, it can update them predictively/speculatively, as long as the sequential execution of the program is unaffected.
If spurious writes to your volatile variable don't break your design, it probably didn't need to be volatile in any context.
For example, it is perfectly legal for the C++03 compiler to transform
int result;
void sum_if_all_positive( std::array<N> ary )
{
int sum = 0;
result = -1;
for( int i = 0; i < N; ++i ) {
if (ary[i] < 0) return;
sum += ary[i];
}
result = sum;
}
into
int result;
void sum_if_all_positive( std::array<N> ary )
{
result = 0;
for( int i = 0; i < N; ++i ) {
if (ary[i] < 0) { result = -1; return; }
result += ary[i];
}
}
(Although such a change would provide better performance than enregistering sum only on a few architectures with cheap memory access and very few registers. The Microchip PIC architecture comes to mind.)
Problem
In C++, `volatile` is treated the same way `const` is: passing a pointer to volatile data to a function that doesn't want the `volatile` modifier triggers a compile error. ``` int foo(int* bar) { /* snip */ } int main() { volatile int* baz; foo(baz); // error: invalid conversion from ‘volatile int*’ to ‘int*’ } ``` Why is it dangerous? It's obvious for the `const` modifier that removing it can break `const` correctness; but is there such a thing as "`volatile` correctness"? I can't figure out how passing a pointer to volatile data as a pointer to non-volatile data could cause problems. EDIT Just so you guys know why I was using `volatile` in the first place: many of Mac OS X's `OSAtomic` family of functions (for atomic increments, decrements, additions, subtractions, compare and swap, etc.) takes `volatile` arguments.