Is it allowed to use a pointer to some type as a pointer to a different type if they have otherwise-identical pointer members that differ only in the constness of the pointed-to values?
Concretely, given the following two structures:
struct type {
char *a;
int *b;
};
struct const_type {
const char *a;
const int *b;
};
Is it allowed to treat a pointer to type
as a pointer to const_type
and vice-versa1, for example passing a type
pointer to a function expecting a const_type
pointer as shown:
int add(const const_type* t2) {
return *t2->a + *t2->b;
}
int is_it_legal() {
int some_int = 42;
char blah[] = "six times and counting...";
type t1 = {blah, &some_int};
return add((const_type*)&t1);
}
My overall motivation here is to have a foo
and const_foo
struct which differ only in the constness of the objects pointed to by their contained embedded pointers. For any function that doesn't modify the pointed-to data, I would like to write a single function (that takes the const_foo
variant) and have it work for both types of objects.
1Evidently in the latter case (using a const_type
as a type
it is not be safe if it results in an attempt to modify a pointed to value in case they were defined const
, but you may assume this doesn't occur).