Mohammad Ghanatian Mohammad Ghanatian - 2 months ago 9
C++ Question

What should be returned as int& when we don't have a proper lvalue in c++?

Today,My professor wrote this code in his computer:

int& at(int index) {
if (index < 0 || index >= maxsize){
cout<<"The index is not valid"<<endl;
return ;}
return elements[index];
}


I'm 90 percent sure that the code was exactly the same as above.
But when I wrote it in my visual studio 2015 I got error.
The compiler wanted me to return an int& in the first return statement.
Can you please help me with this?

Answer

You could do this:

int global_incorrect_value = 42;

int& at(int index) 
{
    if (index < 0 || index >= maxsize)
    {
        cout<<"The index is not valid"<<endl;
        return global_incorrect_value;
    }
    return elements[index];
}

Or this:

std::optional<int*> at(int index)
{
    if(index < 0 || index >= maxsize)
        return {};
    else
        return &elements[x];
}

Or that:

int* at(int index)
{
    if(index < 0 || index >= maxsize)
        return nullptr;
    else
        return &elements[x];
}

Or even that:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        throw std::logic_error;
    else
        return elements[x];
}

Or if you are extreme masochist:

int& at(int index)
{
    if(index < 0 || index >= maxsize)
        explode();
    else
        return elements[x];
}

But you cannot do it "like your professor" - posted code is not even close to legal C++.