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
  • Hmm... interesting point.

    But doesn't the i++ involve an implicit read of i, and making i volatile means that read cannot be optimised-out? Therefore the entire loop can't be optimised-out?

    Well, that's my initial thought off the top of my head - I'll have to go back to my 'C' spec to see if I can back it up...

Reply
  • Hmm... interesting point.

    But doesn't the i++ involve an implicit read of i, and making i volatile means that read cannot be optimised-out? Therefore the entire loop can't be optimised-out?

    Well, that's my initial thought off the top of my head - I'll have to go back to my 'C' spec to see if I can back it up...

Children
  • But doesn't the i++ involve an implicit read of i, and making i volatile means that read cannot be optimised-out?

    Well, I mentioned the standard, but what I actually had in mind is the following. In the code you presented, since the variable i is local to the function, the only conceivable way for it to change in an 'unpredictable' way is when you use a pointer to it elsewhere. Since that didn't happen, nothing prevents the compiler from concluding that the code has no effect.

    There is a sentence in the standard which could support this view:

    What constitutes an access to an object that has volatile-qualified type is implementation-defined

    An implementation might say "If a volatile automatic variable is qualified to be placed in a CPU register by during compilation, the compiler is allowed to optimize away accesses to this variable." It makes sense and it doesn't seem to violate the standard.