5

How do you define constant array of constant objects in C (not C++)?

I can define

int const Array [] = {
    /* init data here */
};

but that is a non-constant array of constant objects.

I could use

int const * const Array = {
    /* init data here */
};

and it would probably work. But is it possible do this with array syntax? (Which looks more clean)

user694733
  • 15,208
  • 2
  • 42
  • 68
  • 1
    I think you are confusing this with pointers. Pointers can be constant, or they can point to constant data, or both. Also note that `int const` and `const int` are completely equivalent expressions, the standard allows both, for the sake of confusing programmers. Gotta love C. – Lundin Oct 03 '11 at 12:48

3 Answers3

11

An array cannot be "constant" -- what is that even supposed to mean? The array size is already a compile-time constant in any case, and if all the members are constants, then what else do you want? What sort of mutation are you trying to rule out that is possible for a const int[]?

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 7
    I think it's confusing to say that an array can't be constant. It's more useful to say that an array is ALWAYS constant. To newbies, arrays seem to act a lot like pointers, but unlike pointers, it's illegal to put one on the left side of an assignment. – Josh Jul 03 '15 at 10:08
  • 2
    This isn't actually an answer. And an answer to your *question* can be found at http://stackoverflow.com/a/31413155/544557 – Jim Balter Jul 14 '15 at 19:49
8

The "double constness" thing applies only to pointers because they can be changed to point to something else1, since the characteristics of arrays are statical by themselves (arrays cannot be changed in size/type/to point to something else) the only const you can apply is to their elements.


  1. so you have the variations "pointer to an int", "pointer to a constant int", "constant pointer to an int", "constant pointer to a constant int".
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

If you want the elements of array do not modify, just use this:

const int Array[];

masoud
  • 55,379
  • 16
  • 141
  • 208