| ▲ | poppadom1982 an hour ago | ||||||||||||||||
You're missing the point. Volatile forces two loads of a value that may have changed in the middle. So the value of "x" may depend on the time/order of load. | |||||||||||||||||
| ▲ | hmry an hour ago | parent | next [-] | ||||||||||||||||
Why is that missing the point? Loading it twice, possibly with different values, is the intended behavior. It's only undefined because the C spec doesn't specify the order of the loads (unlike most other languages which have a perfectly well-defined order for side effects in a single expression). | |||||||||||||||||
| ▲ | AnimalMuppet an hour ago | parent | prev [-] | ||||||||||||||||
Which is, if I understand correctly, the entire point of volatile. Don't use it if you don't want that behavior. And in fact, in the example given, if there is something (another thread or whatever) that can change the value of x, then you don't know what either number will be. Well, in that circumstance, without volatile, it may print the same number both times, but you still don't know what the number will be (unless the read gets optimized away entirely). | |||||||||||||||||
| |||||||||||||||||