[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] volatile...

From: Graham Davies
Subject: Re: [avr-gcc-list] volatile...
Date: Thu, 14 Dec 2006 21:16:32 -0500

<address@hidden> 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.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]