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?
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.
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.
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.
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.
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
.
const PersonRef person = NULL;
is
struct Person*const person= NULL;
so you are consting the pointer and not the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With