typedef pointer const weirdness

Johannes picture Johannes · Dec 14, 2011 · Viewed 14.1k times · Source

please consider the following code:

typedef struct Person* PersonRef;
struct Person {
  int age;
};

const PersonRef person = NULL;

void changePerson(PersonRef newPerson) {
  person = newPerson;
}

For some reason, the compiler is complaining about read-only value not assignable. But the const keyword should not make the pointer const. Any ideas?

Answer

Piotr Praszmo picture Piotr Praszmo · Dec 14, 2011

Note that

typedef int* intptr;
const intptr x;

is not the same as:

const int* x;

intptr is pointer to int. const intptr is constant pointer to int, not pointer to constant int.

so, after a typedef pointer, i can't make it const to the content anymore?

There are some ugly ways, such as gcc's typeof macro:

typedef int* intptr;
intptr dummy;
const typeof(*dummy) *x;

but, as you see, it's pointless if you know the type behind intptr.