You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++链表求和函数报错C4716:'sum'必须返回值,求排查

Fixing the C4716 Error in Your Linked List Sum Function

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:42:56