WarriorWSU
WarriorWSU

Reputation: 11

C++ Linked list and sum issue

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

Upvotes: 1

Views: 547

Answers (2)

Lakshraj
Lakshraj

Reputation: 291

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

Upvotes: 1

Amjad Alsharafi
Amjad Alsharafi

Reputation: 55

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!
}

Upvotes: 3

Related Questions