Say I have the following struct to define list nodes:
struct node {
int data;
struct node* next;
};
And I have this function to get the length of a list:
int Length(struct node* head) {
struct node* current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
Why would I want to do this: struct node* current = head; instead of just iterating over the head?
So, why would this not be ok:
int Length(struct node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
Doesn’t the head lose the scope once it gets inside the Length function, and therefore even if we do head = head->next it won’t be affected outside the function?
Thanks
Your two codes snippets are equivalent.
However, there’s a school of thought that says that you should never modify function arguments, in order to avoid potential programming errors, and to enhance readability (you’re not really modifying the head). To that end, you will often see people defining as many arguments as possible as
const.