[comp.lang.c++] const applied to arrays in C++

schmidt@bonnie.ics.uci.edu (Douglas C. Schmidt) (08/31/88)

Howdy,

   Is the following legal in C++?
   
------------------------------
const int array[] = {4,5,6,7,8};

main() {
   array[3] = 8;
}
------------------------------

Basically, my question is: ``what does const modify in this context?''
Obviously, ``array'' is already a constant, so is const is potentially
redundant.  On the other hand, if it applies to the indexed objects,
as it does with pointers, then the assignment to array[3] should be
illegal.  (If you inspect pages 62 and 63 of Stroustrup you'll see
that he doesn't seem to define what occurs with applying const to
arrays (as opposed to pointers)).

Clearly, 

------------------------------
const int *a = array;

...

a[3] = 7;
------------------------------

is illegal.  But the G++ compiler accepts the earlier code without
hesitation.  It seems to me that the const in this case should apply
to the object, to be consistent with the similar

const int *a;

usage (arrays and pointers being quite similar).  

Can someone please clarify this?  If G++ is correct in accepting this
construct then is there a mechanism for declaring an array of k
constants? 

thanks,

   Doug Schmidt



--
schmidt@bonnie.ics.uci.edu (ARPA)

bs@alice.UUCP (Bjarne Stroustrup) (08/31/88)

Your example
  
 > const int array[] = {4,5,6,7,8};
 > 
 > main() {
 >    array[3] = 8;
 > }

gives me this (using cfront)

"", line 4: error: assignment to  constant

The declaration is correct and so is the compiler's response to the assignment

This question is one that is answered quite clearly in the manual.