Article View: comp.lang.c.moderated
Article #2384Re: const pointer confusion...
From: Jerry Coffin
Date: Mon, 25 Mar 1996 12:21
Date: Mon, 25 Mar 1996 12:21
45 lines
2420 bytes
2420 bytes
In article <4j06gm$7oa@solutions.solon.com>, <mangino@planet.net> says...
> Could someone please straighten me out on this:
>
> 1) const int *p = 10;
> p is a constant pointer to an int, right? While p can be made to
> point to something else, *p can never be assigned to, right?
No. Think of the asterisk as a separator: what's to the left of the asterisk
qualifies what's pointed AT and what's right of the asterisk qualifies the
pointer itself.
I.e. this pointer can pointer at any int, but you can't use it to modify the
int it points at. (without a cast)
> 2) int *const p;
> p is a pointer to an integer. *p can be assigned to, but p can
> never be made to point to another address in memory, right?
Nope. Just the reverse - the pointer can't be modified to point at something
else, but you can modify what it points at.
> 3) int const *p;
> What the heck is this? I can't find anything like this in my
> books, but my compiler thinks everything is hunky doory!???
This is the same as #1. You can change the order of the type and qualifiers
without any real effect as long as they maintain their position relative to
the asterisk. Since volatile is also a qualifier, we can have things like:
int volatile const *
volatile const int *
const volatile int *
and they all mean exactly the same thing. What's to the left of the asterisk
qualifies what's pointed AT and what's to the right modifies the pointer
itself.
(While having something both const and volatile initially seems an oxymoron,
it really isn't: _we_ can't modify something that's const, but that doesn't
mean that some external force can't change it, which is what volatile implies.
Likewise, volatile can be used in cases where we know we'll always read a
particular value (or we don't care about the value read) but in which the mere
act of reading a location may be important in itself.
Later,
Jerry.
Technical Details
Message-ID:
<4j633s$3e7@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4j06gm$7oa@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: jcoffin@rmii.com (Jerry Coffin) Newsgroups: comp.lang.c.moderated Subject: Re: const pointer confusion... Date: 25 Mar 1996 06:21:16 -0600 Organization: TAEUS Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4j633s$3e7@solutions.solon.com> References: <4j06gm$7oa@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com X-Newsreader: MicroPlanet News32 v1.00 Beta Build 302