Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return inside loop for C++ breaks loop?

Tags:

c++

I am reversing a doubly linked list. My function for the same is :

Node* Reverse(Node* head)
{
    // Complete this function
    // Do not write the main method. 
    Node* temp = new Node();
    if ( head == NULL) { return head; }
    while ( head != NULL) {
        temp = head->next;
        head->next = head->prev;
        head->prev = temp;
        if (temp == NULL ) { break; }
        head = temp;
    }
    return head;
}

This works correctly. Instead of using the break command, if I do 'return head' than the function exits the while loop and has a compile error: control reaches end of non-void function [-Werror=return-type]

Node* Reverse(Node* head)
{
    // Complete this function
    // Do not write the main method. 
    Node* temp = new Node();
    if ( head == NULL) { return head; }
    while ( head != NULL) {
        temp = head->next;
        head->next = head->prev;
        head->prev = temp;
        if (temp == NULL ) { return head; }
        head = temp;
    }
 }

What could be the reason behind this?

like image 280
Shubham Lalwani Avatar asked Apr 20 '26 11:04

Shubham Lalwani


1 Answers

The reason is that the compiler doesn't know that temp will always end up being NULL at some point, it only knows the loop can end, and the function will have no return statement.

As CompuChip pointed out, you may add the following line at the end, to appease the compiler:

throw std::runtime_error("Control should never reach this point");

Or you may simply return NULL at the end.

like image 131
StoryTeller - Unslander Monica Avatar answered Apr 23 '26 01:04

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!