C++链表求和函数报错C4716:'sum'必须返回值,求排查
Ah, I spot the issue immediately! The compiler error Error C4716 'sum': must return a value occurs because your function is declared to return an int, but you never actually send a value back to the caller.
Looking at your code:
int sum(struct node *head) { int total = 0; struct node *temp = head; while (temp != NULL) { total += temp->data; temp = temp->next; } }
You correctly calculate the sum of all node values in the total variable, but you forget to return that calculated value. C++ enforces that every function with a non-void return type must include a return statement that provides a value matching the return type.
The fix is straightforward—just add return total; at the end of the function, right after the while loop concludes:
int sum(struct node *head) { int total = 0; struct node *temp = head; while (temp != NULL) { total += temp->data; temp = temp->next; } return total; // This missing line was causing the error! }
That’s all you need to resolve the error. As a quick best practice note: even if logically you know your loop will always exit and reach the end of the function, the compiler requires an explicit return statement for non-void functions to validate the code.
内容的提问来源于stack exchange,提问作者WarriorWSU

