volatile

Barry Margolin barmar at think.COM
Thu Mar 31 16:09:37 AEST 1988


In article <9176 at tut.cis.ohio-state.edu> lvc at tut.cis.ohio-state.edu (Lawrence V. Cipriani) writes:
>	volatile int customer_changeable_var = 0;
>
>	main( )
>		...
>
>	if (customer_chageable_var != 0)
>	{
>		...
>	}
>If the volatile were dropped off, the compiler would be free to
>optimize out the "impossible" code.  A customer changeable global
>variable is a handy way for implementing optional features that
>customers may or may not want; especially in programs that should
>avoid disk i/o.

I don't think volatile is necessary for the above example.  If another
module were linked with this, and it included an "extern int
customer_changeable_var" declaration, it could assign a different
value to this variable.  This is possible because you didn't specify
"static" in your declaration, and it is a global variable.  The
compiler, therefore, cannot assume that this variable has a constant
value just because it doesn't see any assignments in this module.

If you were add the "static" modifier to the declaration, the compiler
WOULD be free to optimize away the unreachable code.  But that's OK,
because in order for the customer to change the variable's value he
would have to edit the source and recompile the module.

The only other case, and maybe this is what you are talking about, is
if the module you are describing is part of the kernel, and the
variable is intended to be updated by patching the core image.  In
that case, if you declare it static then you do, indeed, need the
volatile modifier, but if you don't declare it static you don't have
to declare it volatile, either, because of the reason in my first
paragraph.

Barry Margolin
Thinking Machines Corp.

barmar at think.com
uunet!think!barmar



More information about the Comp.lang.c mailing list