Hacker News new | comments | show | ask | jobs | submit login

Why isn't there a keyword stating "don't optimize this!" in the C Standard? If there is is, please correct me. There are a bunch of similar problems introduced by optimizing compilers that could be solved with such a keyword.

The volatile keyword is effectively that keyword. The trouble is that people want to have their cake and eat it too. They want some optimizations (e.g. a memset that's more efficient than zeroing byte by byte) but not others (e.g. skipping the whole thing).

By specifying volatile and zeroing out the memory in a loop, you're guaranteed that the compiler won't optimize away the zeroing. But if you want something faster, you need to get cleverer, because there's no universal "optimize this way but not that way" command.

C is only ever concerned with side-effects regarding the C abstract machine. Which is not at all the real machine it's running on. The thing is that optimisations only need to verify that they don't change what is observable from within the abstract machine. Which sometimes makes things strange.

One way to inhibit optimisations we used was to declare one of the variables involved as "volatile". I'm not sure about MS, Intel, GCC etc but ours took this as a sign to not run any optimisation passes over code involving volatile variables.

In GCC 4.4 and up you can use the following:

    #pragma GCC push_options
    #pragma GCC optimize ("O0")

    memset(a, 0, 3);

    #pragma GCC pop_options
'volatile' should also work, I don't see why there is any need to rewrite memset. Here is a related question on SO:


Edit: buried at the bottom of that post is another method:


Define "no optimization". On most CPUs, the compiler will have to run some register assignment algorithm. If you insist that every variable load and store must hit memory exactly once, performance will be dreadful, and the compiler probably still would have to run some code to decide which intermediates to spill to memory. Also, compilers typically have to decide on instructions to use. To clear a variable, do you use CLR, XOR, or SUB? In short: there is no clear definition of "don't optimize that"

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact