Is there any difference between these two functions? I mean in-terms of the result returned?
int Length(struct node* head) {
struct node* current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
and this function
int Length(struct node* head) {
int count = 0;
w开发者_开发技巧hile (head != NULL) {
count++;
head = head->next;
}
return count;
}
They are the same. One uses a local 'current' variable to iterate over the list, while the other one uses the same variable that was received through the function arguments.
The returned value will be the same.
The former is the kind of code that would be written by a programmer subscribing to the style rule that says "it is bad practice to modify parameters because they are passed by value and would give the reader a false sense that the function would modify the corresponding argument."
Not necessarily bad advice. It makes the code a little longer, though, but it reads better. Many readers look at the second and have an initial reaction of "wait, what? changing the head? Oh... okay, no it's safe...."
No difference. The second version simply uses the function argument itself as a variable to work with in the body, and that's perfectly legitimate. In fact, it's even slightly more efficient than the first version which make a gratuitous copy.
You couldn't use the second version if the argument were declared const, i.e. int Length(struct node* const head)
-- but since it isn't, you're free to use the argument variable for your own purposes.
精彩评论