Such a restriction seems to produce some unintended undue inconvenience to the programmer in the following case:
Code:
typedef int t_compare_func(const void *, const void *);
struct node *tree_search(struct node *root, const void *keyy, t_compare_func *comp)
{
struct node *cur_item;
int result;
if (root == NULL) return NULL;
cur_item = root;
while (cur_item != NULL) {
result = (*comp)(cur_item->key, keyy);
if (result == 0)
break;
else if (result > 0)
cur_item = cur_item->left;
else
cur_item = cur_item->right;
}
return cur_item;
}
Here, I traverse the tree to find a node whose key member is the same as keyy. And the node found is returned. Nothing in the tree is ever modified. So naturally I would like to const-ify root. But then I am forced to also const-ify cur_item. And the return value also has to be const-ifed as a consequence. Now, (part of) the tree in the calling function cannot be modified! Therefore I have to give up const-ifying root even though nothing in the function modifies the tree. Can I avoid this side effect? Have I just found a legitimate use of const_cast here? O, const_cast is available in C++ only. I guess I need to just cast root like:
cur_item = (struct node *)root;
if I decalre root as a const parameter. Right?