We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I AM NOT UNDERSTANDING THE SITUATION WHEN SHOULD I USE "VOLATILE" WITH VARIABLES ???
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...
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.