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)

1
  • 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. Commented Oct 3, 2011 at 12:48

3 Answers 3

12

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[]?

Sign up to request clarification or add additional context in comments.

2 Comments

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.
This isn't actually an answer. And an answer to your question can be found at stackoverflow.com/a/31413155/544557
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".

Comments

2

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

const int Array[];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.