I have a struct which contains some pointers. I want the value of these to be unmodifiable. But simply writing const infront doesn't make the structs members unmutable
typedef struct{
int *x;
int *y;
}point;
void get(const point *p,int x, int y){
p->x[0]=x;//<- this should not be allowed
p->y[0]=y;//<- this should not be allowed
}
Can someone point me in the right direction.
EDIT:
So it would seem that there is no simple way of using the function prototype to tell that everything belonging to the struct should be unmodifiable
You can do it without typecasting by defining a const point type and a mutable point type, then use a transparent union:
typedef struct{
const int * x;
const int * y;
} const_point;
typedef struct{
int * x;
int * y;
} mutable_point;
typedef union __attribute__((__transparent_union__)) {
const_point cpoint;
mutable_point point;
} point;
Then, you declare your function parameters using either the point or const_point type (never the mutable_point type).
point type object will transparently cast to a const_point type, but not the reverse. This allows you to have a greater degree of type safety.
See here for an example in gcc: http://toves.freeshell.org/xueg/
Note that transparent union was not supported in the last version of C++ I checked (not sure about the latest C++ standard) so you can expect portability issues.
It can also make the code harder to read, and maintain, especially if you have more complex struct. e.g.: you could have point type where either x or y is const, or you may need to embed your point structure into a another struct, e.g. rectangle, for which you might have to define multiple struct for multiple type depending on their constness.
All in all, I'm not sure it's always worth the extra trouble.