This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

"VOLATILE" IS VERY C0NFUSING

I AM NOT UNDERSTANDING THE SITUATION WHEN SHOULD I USE "VOLATILE" WITH VARIABLES ???

Parents
  • If I wrote a compiler, I would be inclined to think that it would be ok to remove the loop, since writes to an auto variable can have no side effets - besides overflowing a too small stack, or producing non-productive bus accesses.

    But I don't think I have seen any compiler who will remove the loop if the variable is volatile.

Reply
  • If I wrote a compiler, I would be inclined to think that it would be ok to remove the loop, since writes to an auto variable can have no side effets - besides overflowing a too small stack, or producing non-productive bus accesses.

    But I don't think I have seen any compiler who will remove the loop if the variable is volatile.

Children
  • Probably, as Mike suggests, the letter of the law would permit the compiler to optimise-out such loops.

    In practice, compiler writers - especially embedded compiler writers - probably realise that their customers do make use of such loops, and so they choose not to.

  • In practice, compiler writers - especially embedded compiler writers - probably realise that their customers do make use of such loops, and so they choose not to.

    Actually, I prefer it this way too: better safe than sorry. It's probably possible to take the spec to such an extreme that the resulting compiler wouldn't be useful for much of anything.
    It reminded me of this thread on the Linux kernel mailing list:
    kerneltrap.org/.../359162

  • In practice, compiler writers - especially embedded compiler writers - probably realise that their customers do make use of such loops, and so they choose not to.

    Optimising away writes to a volatile variable would always be at least a straight violation of the programmer's expressed will, even if the standard can be bent into seemingly allowing it.

    Even setting aside volatile, the GCC guys have a particularly clever idea about optimizing away entire loops: if a non-empty loop body was optimized away, the loop itself is removed, too. If the loop body was empty in the first place, they leave the entire loop alone, under the assumption that nobody would write an empty loop lest they really mean it.