<[EMAIL PROTECTED]> wrote:
> Despite what some have said about this question,
> I don't think it is "stupid"

I agree.  Although this has been discussed before in this very forum, nobody
has so far provided the complete answer this time around.  They have just
provided the most common example of the use of the volatile keyword.  We
think we are experts, above this sort of question, but we don't ourselves
know the whole story.

The C language is described in the standard using the concept of a "abstract
machine" without particular regard to efficiency.  Then, actual
implementations are given permission to deviate from the operation of the
abstract machine so long as at certain points in the program text, called
sequence points, the result of the implementation is indistinguishable from
the results of the abstract machine.  This is where you get to do
optimization.  However, this permission is revoked for expressions referring
to an object that has volatile-qualified type.  In these cases, the
implementation must strictly follow the abstract machine.  This is where
you're forbidden to do optimization.

What almost always gets missed when beginners get the brush off from experts
on this subject is that this applies to write access in addition to read
access.  Not only must the implementation read a volatile variable in
exactly the way the code is written, it must also write a volatile variable
exactly as the code is written.  The canonical example of why this is
important is when the variable is mapped to a hardware register that has a
side effect.  For example, writing to a register might cause the data you
write to be transmitted on a communications link.  If you write txreg =
(some complicated expression), the implementation is obliged to completely
evaluate the expression and perform exactly one write to txreg only if txreg
is qualified as volatile.  If txreg is not so qualified, the compiler is at
liberty to generate code that uses txreg as temporary storage during the
evaluation of the expression, which would result in multiple writes and
extra data appearing on the link.

On the other hand, of course, this is a question about C and not AVR GCC.

Graham.




_______________________________________________
AVR-GCC-list mailing list
AVR-GCC-list@nongnu.org
http://lists.nongnu.org/mailman/listinfo/avr-gcc-list

Reply via email to