4 ms·
Err...volatile just tells the compiler not to cache the value in a register, that's it. If you don't understand volatile you really, really are not the kind of
by tus87 7y ago
Err...volatile just tells the compiler not to cache the value in a register, that's it. If you don't understand volatile you really, really are not the kind of programmer who should even think about using it.
- aidenn0 7y agoThe very first example in TFA shows the compiler doing more than this.
- empiricus 7y agoThis is my understanding of volatile as well: volatile just forces read/write to memory. What a read/write to memory entails is a different story. What happens with no volatile is again another story. If my understanding is wrong, someone please enlighten me.
- tus87 7y agoYou are correct. The author is a delusional narcissistic idiot who believes in a C "memory model" or "virtual machine". It bullcrap. C is just high level assembler, that makes certain optimizations based on certain assumptions. Lots of stuff can break at -O3 at higher. One usually fairly reasonable assumption is that values will not change between reads and writes. Sometimes they do, hence volatile. When you write actual assembly this all becomes irrelevant as you can choose where you store variables and how you access them and when you should consider them "stale". And when you understand code at this low level, C and it's volatile becomes rather plain and boring. There is a LOT of this kind of blogspam on the internet where fools obtain a semi-correct understanding of some low level concepts, then write these long essays about this "dark magic" and making themselves out to be these grandiose elite greybeards hack0rs. And guess where it rises to the front page to the adoration of semi-sentient wannabe dreamer engineers who coo and ga over how smart he is? You guessed it.
- moefh 7y ago"Forcing read/write to memory" is very different from "not caching the value in a register". Optimizations can involve not just caching values in registers, but also reordering operations, calculating things at compile-time and so on. For a trivial example, see this code: int f() { int sum = 0; for (int i = 0; i < 10; i++) sum += i; return sum; } As you can see from [1], a smart compiler will calculate the sum at compile time and make the function simply return the resulting number (i.e., no loop is generated). If you make "sum" volatile, the compiler is forced to do the loop[2]. [1] https://godbolt.org/z/3sX5mU https://godbolt.org/z/3sX5mU [2] https://godbolt.org/z/F5CiDJ https://godbolt.org/z/F5CiDJ