const char* const array initialization with const variables

47 Views Asked by At
const char* const successArray[2] = {"Y", "Z"};

const char* const successA = "A";
const char* const successB = "B";

const char* const failArray1[2] = {successA, successB};
const char* const failArray2[2] = {&(successA[0]), &(successB[0])};

I think I fully understand the differences of const char* vs const char* const and * vs []. But why do the last 2 lines fail with

error: initializer element is not constant
const char* const failArray1[2] = {successA, successB};

Initializing a const array by const variables should clearly be possible, should'nt it? What am I missing?

1

There are 1 best solutions below

3
Blagovest Buyukliev On

The top-level "constness" of successA and successB prevents you from writing code like this:

/* none of these lines will compile */
successA = "C";
successA++;
successA--;

When that identifier is used as an rvalue in expressions, you are effectively copying it temporarily and the constness is irrelevant:

/* top-level const doesn't matter - "successA" won't be modified anyway */
myfunc(successA);
x = successA + 1;

When initialising your failArray1, the compiler doesn't care about the const of your previous identifiers. It sees identifiers referring to some values. Those expressions are not considered constant, hence the error.