This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Does the keyword volatile work?


On Mon, May 12, 2003 at 10:40:28AM -0700, Stephen P. Smith wrote:
> Fergus Henderson wrote:
> 
> >On 12-May-2003, Stephen P. Smith <ischis2@cox.net> wrote:
> > 
> >
> >Firstly, I would suggest using `*(volatile DWORD *)&p1'
> >rather than `(volatile DWORD)p1'.
> > 
> >
> Why would this be better syntax?

Because then p1 will be treated as if it was declared volatile.
With your variant one will first read the value of p1, possibly some
value that has been cached in a register since p1 isn't volatile.
With the *(volatile DWORD *)&p1 syntax the read will be from a memory
location that is treated as volatile and therefore the read is not
allowed to be optimized away.
(This is assuming that you want p1 to be treated as if it was volatile.
Otherwise it doesn't matter.)

> 
> >Secondly, if you want to be sure that the value will be assigned to
> >the target variable immediately, you need to declare the target
> >variable as volatile.
> >
> Why is that the case?  I thought that the cast would be sufficient.
No. Why would you think that.
If an object is declared volatile that essentially tells the compiler
that it is not allowed to optimize away or reorder any reads or writes
from/to that object.  With the 'var1 = (volatile DWORD)p1' syntax
neither var1 nor p1 is declared volatile and thus the compiler can
optimize away accesses to them.  The only thing that is treated as
volatile is the value of p1 in middle of the operation which isn't an
object and therefore the volatile doesn't really matter.

For all intents and purposes your cat to volatile was just a no-op.
You should either declare the variables as volatile or use the
*(volatile DWORD *)&p1 syntax when accessing the variables to make
sure they are treated as volatile.


-- 
<Insert your favourite quote here.>
Erik Trulsson
ertr1013@student.uu.se


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]