[comp.lang.c] const

cc100aa@prism.gatech.EDU (Ray Spalding) (02/02/91)

In article <550@elandes.UUCP> davem@elandes.UUCP (Dave Mathis) writes:
> [...] Here's an example of my trouble.
>typedef struct {
>	int one;
>	int two;
>}foo;
>typedef foo * bar;
>const foo item1 = { 1, 2 };
>const foo item2 = { 3, 4 };
>const foo item3 = { 5, 6 };
>const foo *aray1[] = { &item1, &item2 };
>const bar aray2[] = { &item1, &item2 };    /* gives 'type mismatch' error */

I enjoyed learning, by looking into your question, that ANSI C has both
const pointers and pointers to consts.

I believe the last two lines of code above declare:
	aray1 : array of pointer to const foo
	aray2 : const array of bar == const array of pointer to foo

My compiler accepts both of these fine.  They look OK to me.

>Additionally, some compilers will not accept:
>void
>function1(void) {
>	aray1[0] = &item3;
>}
>	I assume those compilers to be broken.

I agree; aray1[0] is a pointer to a const; aray1[0] itself is not a const.
My compiler accepts this.

>Consistent with the error
>in the declaration  of aray2, none of my compilers accept:
>void
>function2(void) {
>	aray2[0] = &item3;
>}
Nor mine, which I consider a little sarcastic for my taste :-).  It says:
	### Error 68 You can't modify a constant, float upstream,
	win an argument with the IRS, or satisfy this compiler
By the declarations, aray2[0] is itself a const, and thus
can't be assigned to.

>Can someone explain to me, in simple english, what I misunderstand
>about const and/or typedef?

Harbison & Steele ("C, A Reference Manual", 2nd ed.) say:
	The syntax may be confusing [...] [:-)]
and give the following examples:
	int * const const_pointer;
	const int *pointer_to_const;

	typedef int *int_pointer;
	const int_pointer const_pointer;

	or equivalently

	int_pointer const const_pointer;

Notice that the placement of the "const" keyword varies depending
on what is desired, and that "the appearance also changes when
typedef names are used".
-- 
Ray Spalding, Technical Services, Office of Information Technology
Georgia Institute of Technology, Atlanta Georgia, 30332-0715
uucp:     ...!{allegra,amd,hplabs,ut-ngp}!gatech!prism!cc100aa
Internet: cc100aa@prism.gatech.edu