On Feb 25, 12:19 am, david <David.Abdurachma...@gmail.com> wrote:
> No, I am not using it right now, but I though that I should protect at
> least try to make as much protection as I can, so I change "top"
> function declaration with const:
>
> const char* top(stack *item) {
> child *tmp;
>
> if (item->root == NULL)
> return NULL;
>
> tmp = item->root;
> while (tmp != NULL && tmp->next != NULL)
> tmp = tmp->next;
>
> return tmp->value;
>
> }
>
> And I did not change anything in the main code ("mall test code
> fragment"), I do not want to declare "kita" pointer as const too,
> because I might be using it later for other purposes too.
>
> The question was very simple: Is it possible to return a pointer
> through which you wound not able directly change the data it points
> and if it is possible, how to do it. Everyone is going around, but no
> one actually is trying to answer it.
>
> david
The proper way to do that would be to declare
const char *kita;
kita = top(kaka);
and you shouldn't be able to use kita to make any changes to kaka-
>value. However, declaring kita as char *kita (without the const)
would flag a warning, as would assigning another variable char *yutz =
kita. As long as you hold the const in the declaration of the pointer
(read: const char *kita -> kita points to a const char) you should
have no trouble. (If you still do, check the exact location of the
error; you may have forgotten a const. Also possible, but unlikely, is
a compiler error. But let's not go there.)
Note that even if you do declare the pointer as const, it is still
possible to circumvent the const by using a cast (yutz = (char
*)kita).
So the answer to your question is yes and no. You can return a pointer
that the compiler would flag when you use it to change the data;
however, it is not foolproof.
I hope you found this helpful.
-- Marty Amandil
"You can't make anything foolproof, because fools are so ingenious"
-- Corollary to Murphy's Law.
|