Teaching const

Craig Schmackpfeffer craig at srs.UUCP
Mon Apr 11 22:11:15 AEST 1988


In article <9683 at ism780c.UUCP> marv at ism780.UUCP (Marvin Rubenstein) writes:
>In article <27071 at amdahl.uts.amdahl.com> nw at amdahl.uts.amdahl.com (Neal Weidenhofer) writes:
>>	int * const a;
>>decodes as:
>>	a is a constant,
>>	a is a constant pointer,
>>	a is a constant pointer to an int.
>>		(i.e., a cannot be modified but *a can.)
>
>Note that:
>	 int a[1];
>decodes as:
>       a is a constant,
>       a is a constant pointer,
>       a is a constant pointer to an int.
>	       (i.e., a cannot be modified but *a can.)
>
>But there must (?) be some difference between the two.  How do you teach
>this?
>

Of course there is a difference!  The "int * const a" declaration declares 
a pointer to an int.  The "int a[1]" declaration ALLOCATES space for an 
int and "a" itself is not a pointer, but actually the location of the array.

This confusion of pointers and arrays also occurs many times when people
declare an array in one file and then use an extern declaration which says
the variable is a pointer.

To teach this, it is probably easiest to draw the old memory 'boxes' and
show what is held where.  For instance, (sizeof(int)==2, sizeof(int*)==4):

int * const a;    ("a" is located @ 100 and contains address 200)
int b[1];         ("b" is located @ 104, "b"'s value is 104)

*a = *b;  (value taken from 104, put in address @100)

100                         200
+-+-+-+-+                   +-+-+
| 200   |                   |*a |
+-+-+-+-+                   +-+-+
104
+-+-+
| 0 |
+-+-+

Craig
-- 
Craig Schmackpfeffer  @ S.R. Systems
{allegra,rutgers,ames}!rochester!srs!craig



More information about the Comp.lang.c mailing list