If the container interface declares pointers to contained elements as const
?
Task: create a container in C (Note: this is clearly about simple C, not about C ++, nor C #). The container must be provided with pointers to and return pointers to elements.
Somewhat pointless MWE, but the idea extends to useful containers, as well as:
#include <stdio.h> typedef struct { void *data; } container_t; void put(container_t *c, void *data) { c->data = data; } void *get(container_t *c) { return c->data; } int main(void) { container_t c; int x = 42; int *y; put(&c, &x); y = get(&c); printf("value = %d\n", *y); return 0; }
So far so good.
Well, a container should not use pointers to modify stored data. I would like to make this understandable in the interface, change a little:
void put(container_t *c, const void *data) ^new
Now the compiler asks me to make another change, which I really do agree with:
typedef struct { const void *data; } container_t; ^new
Then the compiler asks me to make another change, which is also logical:
const void *get(container_t *c) ^new
And now the compiler complains about y
without being const int *
, which makes me a little unhappy. What is the right way to deal with this?
Create a container without const
? Sometimes I see this library documentation, for example, Glib [ https://developer.gnome.org/glib/2.42/glib-Double-ended-Queues.html#g-queue-push-tail] . But I would really like the "security" const
.
what he might need the return value get
const
throw away? That is, call
y = (int *)get(&c);
I would prefer not to discard the const
inside the get
function, as in
return (void *)c->data;
because I donβt know if the calling item should const
at all. underlined text
source share