Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!wuarchive!uunet!news.uu.net!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c Subject: Re: const and volatile Message-ID: <740@taumet.com> Date: 22 May 91 15:38:55 GMT References: <1991May17.213923.17879@ready.eng.ready.com> Organization: Taumetric Corporation, San Diego Lines: 36 dhoward@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 = but not device = 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 = ; /* illegal: p is const */ *p = ; /* illegal: *p is const */ a = *p; b = *p; /* must read p twice, cannot optimize */ -- Steve Clamage, TauMetric Corp, steve@taumet.com