I am learning about linked lists in my programming class right now. The following code is what compiles and works:
struct Node {
int data;
Node *link;
};
// this function compiles and works
size_t list_length(const Node* head_ptr) {
size_t size{};
for ( ; head_ptr != nullptr; head_ptr = head_ptr->link) {
size++;
}
return size;
}
The following implementation of the list_length function does not compile:
// this function gives a compile times error
size_t list_length(const Node* head_ptr) {
size_t size{};
Node *ptr = head_ptr;
for ( ; ptr != nullptr; ptr = ptr->link) {
size++;
}
return size;
}
I am confused about the const qualifier. In this case, I know it means that the argument cannot be changed within the function. I have two questions:
In the version of list_length that works, why can the for-loop change the value of head_ptr if head_ptr is a const variable? As the loop iterates, is it not changing the value of head_ptr?
In the version of list_length that does not compile, why can I not assign the value of head_ptr to new pointer variable?
In the second case you are trying to create a pointer to a non-
constNodefrom a pointer toconstone. The compiler will not allow this as it may cause problems elsewhere. You can either use a pointer to aconst Nodefor the copy, or useconst_castto bypass the error check. So either:or
In case 2 here, the compiler allows the cast as you are telling it that you know what you are doing.