This site has tilted so far toward the political (or personal) lately that it almost feels weird to be writing about technical stuff again. Here goes, and I hope this doesn’t bore my non-technical readers to death.

One of the most misunderstood parts of C/C++ is the volatile keyword. Its meaning can be stated simply as that it disallows the compiler from optimizing out references to a variable. The problem comes about because many programmers assume that it means all optimizations involving that variable are disallowed, but the careful reader will note that the above definition says nothing about adding references. This became a problem several years ago at Dolphin, where we had a pretty innocent-looking piece of code:

a = b = *c;

The compiler generated code that dereferenced c twice, as though we had written

a = *c;
b = *c;

instead. This seemed rather silly, since adding memory references (and particularly pointer dereferences) is generally a good way to make code run slower instead of faster, but it was perfectly legal even with c declared as a pointer to a volatile value. The problem was that c didn’t actually point to a memory location. It pointed to a memory-mapped register, and accessing that register twice had undesirable side effects.

I think we eventually worked around the problem by creating (yet another) temporary variable to hold *c, but the way that volatile turned out to be insufficient has bothered me ever since. I decided at the time that there should be a second keyword – let’s call it fragile – that is the inverse of volatile; tagging a variable as fragile means that the compiler cannot add references. If both keywords were used, the effect would be that no optimizations (or “pessimizations”) at all involving that variable would be allowed and that the generated code would have to reproduce the accesses as they were expressed in C — exactly what many programmers think volatile alone does now. I believe that some specialized compilers have added keywords more or less like this but, as far as I know, it has never made it into a standard. It still seems like a strange omission.