Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!gem.mps.ohio-state.edu!tut.cis.ohio-state.edu!unmvax!bbx!bbxsda!scott From: scott@bbxsda.UUCP (Scott Amspoker) Newsgroups: comp.std.c Subject: Re: volatile required? Message-ID: <187@bbxsda.UUCP> Date: 29 Sep 89 15:57:33 GMT References: <712@Aragorn.dde.dk> <30292@news.Think.COM> Reply-To: scott@bbxsda.UUCP (Scott Amspoker) Organization: Basis International, Albuquerque, NM Lines: 41 In article <30292@news.Think.COM> barmar@kulla (Barry Margolin) writes: >In article <712@Aragorn.dde.dk> ct@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