Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"control reaches end of non-void function" warning in eclipse c++ but no compile- or run-time errors

Here's my code:

Composer& Database::GetComposer (string in_last_name)
{   
    for (int i = 0; i < next_slot_; i++)
    {
        if (composers_[i].last_name() == in_last_name)
             return composers_[i];
    }
}

The idea is to iterate over an array of Composer objects and return a reference to the object whose last_name field matches "in_last_name." I understand what the warning is telling me, namely that it's possible that the function won't return anything (if, say, the user provides an invalid last name). My question is, how can I avoid this? I tried adding "return 0" and "return NULL" after the for loop and it wouldn't compile. Should this method throw an exception if it finds nothing?

like image 966
wbr Avatar asked Dec 07 '11 04:12

wbr


1 Answers

Your function is declared to return a Composer&, that is, a reference to a Composer. If your function fails to return a suitable reference, and the caller tries to use the return value for something, undefined behaviour will result.

If your function may legitimately fail to find what it's looking for, you may want to change the return type to a pointer instead of a reference. That would give you the option to return NULL:

Composer* Database::GetComposer (string in_last_name)
{   
    for (int i = 0; i < next_slot_; i++)
    {
        if (composers_[i].last_name() == in_last_name)
             return &composers_[i];
    }
    return NULL;
}

Alternatively, you could throw an exception when your function fails to find the target.

like image 93
Greg Hewgill Avatar answered Sep 29 '22 01:09

Greg Hewgill