Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef pointer const weirdness

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?

like image 605
Johannes Avatar asked Dec 14 '11 12:12

Johannes


People also ask

Can a const pointer be modified?

Because the data type being pointed to is const, the value being pointed to can't be changed. We can also make a pointer itself constant. A const pointer is a pointer whose address can not be changed after initialization.

What is a typedef pointer?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.

What does const pointer mean?

A constant pointer is one that cannot change the address it contains. In other words, we can say that once a constant pointer points to a variable, it cannot point to any other variable. Note: However, these pointers can change the value of the variable they point to but cannot change the address they are holding.

Can you increment a const pointer?

When we have compiled the code of the const.cc file, it gives us the error at line 10. As the pointer was constant, the error states that the “cptr” is read-only and can't be incremented as expected.


2 Answers

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.

like image 113
Piotr Praszmo Avatar answered Oct 11 '22 12:10

Piotr Praszmo


const PersonRef person = NULL; 

is

struct Person*const person= NULL; 

so you are consting the pointer and not the object.

like image 38
Jens Gustedt Avatar answered Oct 11 '22 13:10

Jens Gustedt