Re: (C lang) how do compilers deal with volatile, const, and register keywords?

James Jones <>
5 Apr 2000 22:22:39 -0400

          From comp.compilers

Related articles
(C lang) how do compilers deal with volatile, const, and register keyw (Scott Bissett) (2000-04-01)
Re: (C lang) how do compilers deal with volatile, const, and register (James Jones) (2000-04-05)
| List of all articles for this month |

From: James Jones <>
Newsgroups: comp.compilers
Date: 5 Apr 2000 22:22:39 -0400
Organization: Microware Systems Corporation
References: 00-04-022
Keywords: C, optimize, practice

The moderator covered "register"; now, for the qualifiers:

An object of volatile qualified type is supposed to be handled just as
described in the language standard--i.e. you can't do a bunch of
clever optimizations on it. Canonical examples:

volatile short *ip;

while ((*ip & DEVICE_READY) == 0)

i.e. the stock busy wait aka spin lock for, say, memory mapped I/O.
Were it not for the volatile qualification, a compiler would be within
its rights to generate code as if you'd written

if ((*ip & DEVICE_READY) == 0) {
for (;;)
/* whirrr... */;

because obviously there's nothing in the original loop that changes

Later on, one might see

char status;

status = *ip >> 8;

Gee...that's just the most significant byte, so why load the whole
short? A compiler would thus emit code to just load the most
significant byte and avoid the shifting, even though the memory mapped
I/O device will give garbage results if you don't read the whole
short, were it not for the volatile qualification.

Some of the gotchas are target dependent, so volatility has to be seen
throughout code generation, at least; for example, on the 68000, but
not on later 68xxx, the clr instruction, which sets its operand to
zero, turns out to actually read the operand--so that you can't use it
on a volatile qualified object, but have to do a move and explicitly
give the immediate operand.

Const qualification is just a promise that code the compiler generates
won't modify the object so qualified. (Hence the seemingly self-
contradictory "const volatile" combination, which comes in handy for
read-only memory mapped I/O ports. Actually, DEC's VMS C compiler
used the far more appropriate "readonly", but the standard is the
standard.) Const qualified objects can, in theory at least, be placed
in a read-only area, though life turns ugly when const qualification
is applied to things of pointer type, unless you have memory mapping
hardware to paper over the difficulties. (For example...say you have a
global variable

int j;

and also

int * const jp = &j;

and are thinking of putting jp in the code area. What will you set it
to? You _do_ want your code to be re-entrant, don't you? ;-)

James Jones

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.