'control reaches end of non-void function (adding a node at tail)
*SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
SinglyLinkedListNode *t=new SinglyLinkedListNode(data);
SinglyLinkedListNode *last{head};
if(head==nullptr)
{
head=t;
return head;
}
else if(last->next==nullptr)
{
last->next=t;
last=t;
return head;
}
else
{
while(last)
{
if(last->next==nullptr)
{
last->next=t;
last=t;
return head;
}
last=last->next;
}
}
}
This function adds a node to the end of the linked list. If I am writing a return statement outside of the if-else block, is working fine but as above it's giving an error. why?
Solution 1:[1]
The message says that there is at least one code path that's missing the return - check your last else. If the while exists because last==nullptr, there's no return.
Solution 2:[2]
The while(last) theoretically can exit as far as static analyzer is concerned. And it even can be right if you accidently re-entered this function from different thread.
The code can be rearranged to streamline flow. The purpose of your function is that you have to iterate through values of next and if next is nullptr, you have to replace it.
Are you sure you always have to return head? That looks like a error\bug.
{
SinglyLinkedListNode *t =new SinglyLinkedListNode(data);
if(!head)
return head = t;
SinglyLinkedListNode *last{head};
while (last->next)
last = last->next;
// we go here if last->next is nullptr,
// earliest case would be head->next == nullptr
return (last->next = t);
}
No matter what, this function would return something at any path.
PS: I really hope that constructor looks like SinglyLinkedListNode(Data &d) : data(d), next(nullptr) {} or yo'll have UB and possible infinite loop on your hands
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MSalters |
| Solution 2 |
