volatile required?

Scott Amspoker scott at bbxsda.UUCP
Sat Sep 30 01:57:33 AEST 1989


In article <30292 at news.Think.COM> barmar at kulla (Barry Margolin) writes:
>In article <712 at Aragorn.dde.dk> ct at dde.dk (Claus Tondering) writes:
>>	  int p=3, *q=&p;
>>	  *q=4;
>>	  printf("%d\n",p);
>>Is it acceptable that this program prints 3 instead of 4? The variable
>>p is not declared volatile, and therefore the fact that *q=4 assigns
>>4 to p may be considered a side effect.
>
>No, the program must print 4.  Since p's address is taken, the
>optimizer should know that it isn't safe to assume that only
>assignments to p will modify its value.

I noticed that the suject line refers to "volatile".  The code
example does not present a situation for the volatile keyword.  The
problem presented in the code example is deals with an optimizer
headache known an "aliasing".  Some compilers provide a 
"don't-check-aliasing" option that may generate somewhat faster code
but could also generate incorrect code.

The volatile keyword is used when dealing with data that could be
modified by an interrupt or signal handler.  Consider the following
loop waiting for a flag indicating that some external event occurred.
It is assumed that the interrupt/signal handler will set the flag:

while (!flag)
    ; /* loop until flag set */

The optimizer notices that flag is never changed in the loop and may
do some strange things.  The value for flag may be loaded into
a register avoiding further access to the actual memory location
of flag.  Declaring flag as "volatile" tells the compiler that
someone else is also using that memory location and that the
value could "magically" change at any time.  There is no way a
data flow analyser could determine that.


-- 
Scott Amspoker
Basis International, Albuquerque, NM
(505) 345-5232



More information about the Comp.std.c mailing list