Search code examples
cavr

AVR C - How does the const qualifier behaves in a look up table declaration?


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?


Solution

  • 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).