11

If I create a global array of const values, e.g.

const int SOME_LIST[SOME_LIST_SIZE] = {2, 3, 5, 7, 11};

is it possible for SOME_LIST to be modified in any way?

How can I write this such that SOME_LIST points to a const memory location, and is a const pointer itself (i.e. cannot be pointed somewhere else)?

Casey Kuball
  • 7,717
  • 5
  • 38
  • 70

2 Answers2

20

There are 3 main examples of pointers which involve the "const" keyword. (See this link)

Firstly: Declaring a pointer to a constant variable. The pointer can move, and change what is it pointing to, but the variable cannot be modified.

const int* p_int;

Secondly: Declaring an "unmovable" pointer to a variable. The pointer is 'fixed' but the data can be modified. This pointer must be declared and assigned, else it may point to NULL, and get fixed there.

int my_int = 100;
int* const constant_p_int = &my_int;

Thirdly: Declaring an immovable pointer to constant data.

const int my_constant_int = 100; (OR "int const my_constant_int = 100;")
const int* const constant_p_int = &my_constant_int;

You could also use this.

int const * const constant_p_int = &my_constant_int;

Another good reference see here. I hope this will help, although while writing this I realize your question has already been answered...

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
12

The way you have it is correct.

Also, you don't need to provide SOME_LIST_SIZE; C++ will figure that out automatically from the initializer.

KRyan
  • 7,308
  • 2
  • 40
  • 68
  • Just to confirm, if I tried to point it somewhere else or memset it, a compiler error would be thrown? – Casey Kuball Aug 07 '12 at 17:23
  • 1
    @Darthfett: Yes, it would. Someone particularly malicious might be able use `const_cast` on it, but as a not-pointer, I'm fairly certain that's treading into undefined behavior territory. – KRyan Aug 07 '12 at 17:25
  • 3
    Of course: an array cannot be relocated, and `memset` would complain that you are giving to it a `const` pointer. Obviously you could bypass this last protection with a `const_cast`, but then you go into UB-land (it may result in a crash at runtime). – Matteo Italia Aug 07 '12 at 17:25
  • 3
    `const int SOME_LIST[]` decays to `const int *` when passed to a function. Isn't the OP asking for a way to define `SOME_LIST[]` such that it will decay to `const int * const`? – U007D Jan 16 '16 at 16:38