1

I keep getting an error with the code below and I don't know why.

int sum(struct node *head)
{
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        total += temp->data;
        temp = temp->next;
    }
}

Error C4716 'sum': must return a value

2
  • 4
    Because sum promises to return an int but does not. A return total; at the end of the function is probably in order. I suspect a function with a name like sum should return the calculated sum, and you went through all the trouble of computing it. Commented Mar 29, 2018 at 4:55
  • You know, I was about to complain the function doesn't have a closing bracket when I noticed that }}. That's a poor way to place a curly brace, it gets lost in the jumble of code and doesn't indicate where a function ends. I suggest you give up this style asap, because it will make collaborating with other developers harder. Commented Mar 29, 2018 at 4:58

2 Answers 2

3

Just like the the error message is saying, you need a return statment:

int sum(struct node *head)
{
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        //cout << temp->data << '\n';    //debug
        total += temp->data;
        temp = temp->next;
    }
    return total; // <-- add this!
}
Sign up to request clarification or add additional context in comments.

Comments

1

As you write int sum(struct node *head) that means your funtion should return a integer value. So what you can do is that you can add a return statement at the end of your funtion.

Something like that

    int sum(struct node *head)
    {
    int total = 0;
    struct node *temp = head;
    while (temp != NULL)
    {
        total += temp->data;
        temp = temp->next;
    }
    return total;
    }

And the statement where you call this function just assign that function to any integer variable.

int t = sum(head);

Hopefully that helps

2 Comments

int t = sum(*head); may be a guess too far. Odds are good that head would not need to be dereferenced.
If their is any sort of error or mistake you can edit it sir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.