why do you need volatile?

Tim Olson tim at amdcad.AMD.COM
Fri Jun 3 13:25:26 AEST 1988


In article <3754 at pasteur.Berkeley.Edu> faustus at ic.Berkeley.EDU (Wayne A. Christopher) writes:
| In article <15735 at brl-adm.ARPA>, reg%lti.UUCP at bu-it.bu.edu (Rick Genter x18) writes:
| > 	for (A = 1.0, i = 0 ; i < iCalcRep ; i++) {
| > 		if (! bContinueCalc)
| > 			break;
| > 		A = Savage (A);
| > 	}
| > ... should be declared
| > 
| > 	volatile BOOL bContinueCalc = FALSE;
| > 
| > otherwise the C compiler is perfectly justified taking the test of
| > bContinueCalc out of the for loop, thus invalidating the whole use
| > of the variable.

Actually, because there is a function call in the loop, the test cannot
typically be removed, unless the compiler can trace the program flow and
ensure that bContinueCalc is not modified elsewhere.  However, if there
were no function call in the loop, then the compiler *is* justified in
moving the test out of the loop, since it is invariant.

Here is an example, from the MetaWare 29000 C compiler:

=== non-volatile, function call in loop ===
;int bool;
;
;int f()
;{
;	int i = 0;
;	
;	for (;;) {
;		if (bool)
;			break;
;		i = A(i);
;	}
;	return i;
;}
	const	gr96,0	; (0x0)
	const	lr4,_bool
	consth	lr4,_bool
L00012:
	load	0,0,gr121,lr4		<-- note that load of "bool",
	cpeq	gr121,gr121,0		<-- and comparison are in the loop
	jmpt	gr121,L00014
	nop
	.
	.

=== non-volatile, no function call in loop ===
;int bool;
;
;int f()
;{
;	int i = 0;
;	
;	for (;;) {
;		if (bool)
;			break;
;		++i;
;	}
;	return i;
;}
	const	gr121,_bool
	consth	gr121,_bool
	load	0,0,gr121,gr121		<-- "bool" is loop-invariant, so it
	const	gr96,0	; (0x0)		<-- is moved out, along with the
	cpeq	gr121,gr121,0		<-- comparison to zero!
L00012:
	jmpt	gr121,L00014
	nop
	jmpi	lr0
	nop
L00014:
	jmp	L00012
	add	gr96,gr96,1


=== volatile, no function call in loop ===
;volatile int bool;
;
;int f()
;{
;	int i = 0;
;	
;	for (;;) {
;		if (bool)
;			break;
;		++i;
;	}
;	return i;
;}
	const	gr96,0	; (0x0)
	const	gr120,_bool
	consth	gr120,_bool
L00012:
	load	0,0,gr121,gr120		<-- load is not hoisted because
	cpeq	gr121,gr121,0		<-- of volatile declaration.
	jmpt	gr121,L00014
	nop
	jmpi	lr0
	nop
L00014:
	jmp	L00012
	add	gr96,gr96,1


	-- Tim Olson
	Advanced Micro Devices
	(tim at delirun.amd.com)



More information about the Comp.lang.c mailing list