(Ab)using pointers to const objects

Neil Readwin nreadwin at micrognosis.co.uk
Mon Oct 15 21:50:03 AEST 1990


I am trying to understand what I can do with pointers to const and non-const
objects.  The VAX C manual (not much of a reference, I admit) says 'if you 
attempt to access a const object using a pointer to that object not declared 
const then the result is undefined'.

I am uncertain whether 'not declared const' applies to 'object' or
'pointer', but I assume it means 'object'.

This would mean that you cannot *read* a const object using a pointer to
a non-const object. Or to put it another way ...

int const foo = 1;
int *bar = &foo;	/* non-const pointer to const, even gcc bitches */
int  qux = 1;
int const *baz = &qux; /* Pointer to constant int */
int wibble;

wibble = *bar;	/* Not allowed ! */
wibble = *baz;	/* This is OK */

Do other compilers that support const have this restriction on read access ? 
Does the standard apply any such restriction ? (This is less important :-)

Lastly, can anyone suggest a machine architecture where the reference to
bar could fail and the reference to baz could succeed ? When we first
looked at this we thought that a machine with segmented or relative 
addressing might implicitly modify the pointer to a const, but this would 
not allow the reference to baz to work. (Wild speculation on possible
architectures should probably be restricted to mail :-) Neil.
-- 
 Disclaimer: 818  Phone: +44 71 528 8282  E-mail: nreadwin at micrognosis.co.uk
 W Westfield: Abstractions of hammers aren't very good at hitting real nails



More information about the Comp.lang.c mailing list