1

I found the following code in a forum and i was wondering how does the const qualifier behaves in it?

const uint8_t data[] = { 15, 3, 41, 76, 2, 9, 5 };

val = data[5];

Now, as i understand the const qualifier makes the variable data[] read-only so that, in this example, the contents of the array can't be modified. What confuses me is that the qualifier is being applied to an array, which is a pointer so the contents of the array can be modified but the pointer itself can't.

Am i right?, or is the content of the array read-only?

unwind
  • 391,730
  • 64
  • 469
  • 606
Carlos M.
  • 147
  • 9
  • Possible duplicate of [Is an array name a pointer?](https://stackoverflow.com/questions/1641957/is-an-array-name-a-pointer) – Bo Persson May 02 '18 at 09:49

1 Answers1

7

an array, which is a pointer

No, no, no. Arrays are not pointers. A pointer is an address (usually 4 or 8 bytes on current desktop systems). An array is a sequence of contiguous objects in memory, one after the other.

In most expressions, arrays decay to pointers: when you use the name of an array, it is implicitly converted to a pointer to its first element. But that is just a conversion, just like 1 converts to 1.0 when initialising a variable of type double.

Given the above, the answer is clear: data is an array of 7 objects of type const uint8_t, which means its contents cannot be modified. In expressions, data will implicitly convert to type const uint8_t * (pointer to constant 8-bit unsigned integer).

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455