volatile: a summary

der Mouse mouse at mcgill-vision.UUCP
Mon Jun 20 18:56:30 AEST 1988


In article <796 at l.cc.purdue.edu>, cik at l.cc.purdue.edu (Herman Rubin) writes:
> [pseudo-random numbers]  At each stage, one wishes to get the _next_
> number.  There are many ways to do this; the simplest, and one of the
> slowest, is to do something like

> 	x = random();

> each time one is needed.  Now it is essential that the computation of
> random() be done at _each_ call.  Volatile beats all of the kludges I
> have seen to accomplish this.

Volatile is not necessary to ensure this.  The compiler is required to
behave as if the calls were made as written; since random() has side
effects, this involves performing those side effects.  This means
either actually performing the calls or somehow moving the computation
that goes on in random() into the caller - effectively inlining the
call.  Either way is fine: you get a new "random" number each time
flow-of-control passes that point, which is what you wanted.

The compiler is not permitted to use CSE as an excuse to throw away
routine calls (in the absence of hard information that it's safe to do
so, for example, a declaration that the routine is a pure function, or
source code to it being available at the time).  Imagine what could
happen if this were done to read(), for example....

					der Mouse

			uucp: mouse at mcgill-vision.uucp
			arpa: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list