(Ab)using pointers to const objects

Chris Torek chris at mimsy.umd.edu
Fri Oct 19 09:36:33 AEST 1990


In article <1990Oct15.115003.29238 at micrognosis.co.uk>
nreadwin at micrognosis.co.uk (Neil Readwin) writes:
>I am trying to understand what I can do with pointers to const and non-const
>objects. ...

If you replace the word `const' with `readonly', everything will suddenly
make sense.

	const int x = 12345;

produces a read-only variable called `x' whose value is 12345.  Any
attempt to change x (with `x = 0;', e.g.) will give an error.  An attempt
to set a pointer to point to x will get an error unless the pointer
itself points to readonly `int's:

	const int *p1; int *p2; p1 = &x; p2 = &x;

The assignment `p2 = &x;' is `bad' because p2 points to changeable `int's
and x, though an int, is not changeable.  If you insert a cast you can
`slip this by':

	p2 = (int *)&x;

but if you assign through the resulting pointer (`*p2 = 0;'), the
behaviour is undefined (meaning ANYTHING can happen, ANY time: if the
computer has access to a time machine it can go back and kill your
grandfather, or whatever).  Most likely: a runtime error, or x changes;
less likely: a compile time error; fairly unlikely: the computer
explodes.

In the other direction, things are better:

	int y; const int *p1; int *p2; p1 = &y; p2 = &y;

Both assignments are legal, because in both cases `y' is an int.
Although p1 points to readonly ints rather than regular ints, the
only effect this has is to make attempts to change *p1 illegal.
Note that *p1 can still change; it is only changes through the
name `*p1' that are illegal:

	y = 1;
	printf("%d\n", *p1);	/* prints 1 */
	y = 2;
	printf("%d\n", *p1);	/* prints 2 */
	*p1 = 3;		/* is an error */

In other words, `*p1' is NOT constant, just read-only.  Every time
you read it you may get a different value.

(This is the sort of thing that makes alias analysis in C difficult.
Not impossible, but definitely difficult.  You can answer the question
`does *p1 change' with `yes' or `no' in many actual programs, although
there exist unsolvable cases.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list