I’m a student who still doesn’t quite get const parameters. I understand why this won’t work:
#include <stddef.h>
struct Node {
int value;
Node* next;
};
Node* cons(const int value, const Node * next) {
Node * tmp = new Node();
tmp->value = value;
tmp->next = next;
return tmp;
}
int main () {
const Node * k;
k = cons(1, NULL);
Node * p;
p = cons(2, k);
}
This is because I am “casting away” the constness of k by giving p its address.
What I intended by marking the parameter “const” was to say that my method won’t change the node directly. Where as if I were to pass in (Node * next), I would feel like there is no guarantee that my method is not dereferencing that pointer and messing up the node. Maybe this is foolish, since there is then no guarantee that later on the const Node I passed a pointer to won’t get changed via the new pointer to it. It just seems strange that: in this method cons, all I am doing is pointing a new pointer at ‘next’ – I never touched next, just pointed – and yet that is enough to break the constness.
Maybe I have just underestimated the strength of the “const” promise.
Thanks!
The issue is that your
nextargument is of typeconst Node *(read: a pointer to a constant Node object), whereas theNode::nextfield is of typeNode *(a pointer to a non-const Node object).So when doing
You try to make the compiler take a pointer to a const
Nodeobject and assign it to a pointer to a non-constNode. If this worked, it would be a simple way to circumvent constness, because suddenly people could modify thenextargument simply by dereferencingtmp->next.