gjcamann
gjcamann

Reputation: 651

Why can I not assign a const pointer to a const pointer in a struct?

Here is an example below where I try to assign a const pointer to a const pointer in the struct and the compiler won't let me. But I can assign a literal without any problem. I've also tried this case with out any const's and with some const's if you know what I mean, but I still don't see why the compiler is cool with the literals but as issues with the char* in the assignment.

const char* cat_surname = "Snack";

typedef struct
{
    const char* first;
    const char* last;
}PET_T;

PET_T dog =
{
        "Rover",    // OK
        "Cateater"  // OK
};

PET_T cat =
{
        "Tasty",    // OK
        cat_surname // ERROR :-(
};

I get this compiler error:

error: initializer element is not constant

Using Arch Linux gcc version 4.8.2 20140206 (prerelease) (GCC)

Upvotes: 1

Views: 278

Answers (1)

chux
chux

Reputation: 154146

To avoid the problem, make cat_surname an array of const char rather than a pointer to const char.

const char cat_surname[] = "Snack"; 
PET_T cat = {
  "Tasty",
  cat_surname
};

Note: The use of const does not mean that the object is constant. It's a bit more like "read-only". Below, i may have different values as foo() is called, but the function foo may not change it.

void foo(const int i) {
  i = 5; // compile time error
}

The use of const in const char* cat_surname = "Snack"; does not imply cat_surname can not change value. const here means that the data cat_surname points to should not be attempted to be change as follows:

*cat_surname = 'X'; // bad

The compiler error "initializer element is not constant" wants a true constant. An array is that: the array's first element is always at the same address.

@Matt McNabb brings up a good point that the initial value of cat.last could be cat_surname. I do not have a strong reason why C does not allow that.

Upvotes: 2

Related Questions