const and volatile

Stephen Clamage steve at taumet.com
Thu May 23 01:38:55 AEST 1991


dhoward at ready.eng.ready.com (David Howard) writes:

>Questions on const and volatile:

>I declare:
>	const unsigned char *device = (unsigned char *)0x600000b;
>Then I do:
>	*device = 0x01;
>The compiler complains:
>	'attempt to modify a const'

The compiler is correct.  You say later that you want the pointer to be
const, not what it points to.  In that case, you need to say this:
	unsigned char * const device = (unsigned char *)0x600000b;
This makes 'device' const, rather than what it points to.  You will
now be able to write
	*device = <something>
but not
	device = <some address>

The same thing applies to volatile, where T is some type:
	volatile T *p;	/* p not volatile, points to a volatile object */
	T * volatile p;	/* p is volatile, the object is not */

For a pointer to a memory-mapped input device or clock, you might want
something like this:
	const volatile T * const p = (const volatile T*) 0xc000abcd;
This says that p cannot be assigned to (it is const), and that it points
to an object which cannot be assigned to, and which might change
spontaneously.  That is:
	p = <some address>;	/* illegal: p is const */
	*p = <some value>;	/* illegal: *p is const */
	a = *p; b = *p;		/* must read p twice, cannot optimize */
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list